How to Load PowerShell Functions On-Demand? - powershell

In my personal PowerShell profile that loads whenever I start PowerShell, I want to include a set of functions by calling a function.
So I want to do something like this:
function loadMyFunctions{
. \MyFunctions.ps1
}
Now, in MyFunctions.ps1 I have a function:
function bobtest{
write-host "My name is Bob Newhart."
}
I am able to load the script MyFunctions.ps1, but after that is loaded I am not able to call bobtest in the console - I get the error message The term bobtest is not recognized...
However, if I just load the script outside the function then that script is loaded and I can call bobtest normally - but that means that I can't just not load MyFunctions when the profile is loaded - I have to load MyFunctions and cannot choose.
You see, I want to load the other functions on demand and not have them available until I choose.
Is there another way to do this or can it even be done?

Have a look at this page, How to Create PowerShell Modules and Manifests.
This will enable you to create a module which will have all your custom functions! Then inside of your loadMyFunctions cmdlet add Import-Module NewModuleName.
This will enable you to use your cmdlets.
Hope this Helps,
Lachlan

Best way is to use modules. But still if you want to get in some different ways , then you can try with your approach.
See the below screenshots which I have performed.
I have a function addition which simply does addition and I saved it as funct1.ps1
Now I am calling the same function from another function of the other script just using dot source without using as module and it results me properly.
Funct1.ps1
Triggered the function from another function in another script .
Hope it helps...!!!

Related

Using global variables in a ps1

I can't seem to find good enough solution to my problem. Is there a good way of grouping variables in some kind of file so that multiple scripts could access them?
I've been doing some work with Desired State Configuration but the work that needs to be done cannot be efficiently implemented that way. The point is to install Azure Build Agent on a server and then to configure it. There are some variables that really should not be inside a script file just copypasted like Personal Access Token. I just want to be able to easily change it without the need to go inside every script that would be using it. In DSC you can just make a .psd1 file and access the variables like for example AllNodes.NodeName. The config file invocation and parameters look like this:
.\config.cmd --unattended --url $myUrl --auth PAT --token $myToken --pool default --agent "$env:COMPUTERNAME" --acceptTeeEula --work $workDir'
I want to make the variable $myToken accessible from outside file for better security and having a centralized place from where I can change values. $myUrl is also important to have access to due to it changing with new update to Build Agent.
Thank you in advance for your effort. If anything is not clear please let me know.
I have two very different answers to your question, although either one of them may miss your point.
First, it's possible to define veriables inside your profile script. Most people only use the profile script to define a library of functions or classes. But a variable can be made global the same way.
I have a variable named $myps that identifies the folder where I keep my PS scripts (in subfolders).
When I start a session I generally switch to this directory (oops, I called it a folder above.
The second way involde storing values of variables in a CSV file, while the names are stored in the CSV header.i then have a quickie little comandlet that steps through a CSV file, record by record, generating different expansions of a template each time through.
These values are not quite global, but they can be used in more than one context.
Thank you for the help. Those are very useful solutions in some cases, but I dug a bit deeper and found solution that suits my purpose. Basically if you have a psd1 file suited for DSC use you can also access its content via normal ps1 file. For example:
NonNodeData =
#{
Pat = 'somePAT'
}
Let's say this section of a psd1 file called ENV.psd1 is on your local machine in C:/Configuration
To access the content of this file you have to make a variable inside your script and use Import-PowerShellDataFile like so:
$configData = Import-PowerShellDataFile -Path "C:\Configuration\ENV.psd1"
And now you are free to use anything stored inside ENV.psd1. For example if I want to extract my PAT from config file to be able to store it in a variable in the script:
$myPat = $configData.NonNodeData.Pat
Thanks to that I can just pass $myPat as a parameter when invoking config.cmd like so:
.\config.cmd --unattended --auth PAT --token $myPat
Keeping my code cleaner and easier for any future updates.

What is the full command for gdal_calc in ipython?

I've been trying to use raster calculation in ipython for a tif file I have uploaded, but I'm unable to find the whole code for the function. I keep finding examples such as below, but am unsure how to use this.
gdal_calc.py -A input.tif --outfile=result.tif --calc="A*(A>0)" --NoDataValue=0
I then tried another process by assigning sections, however this still doesn't work (code below)
a = '/iPythonData/cstone/prec_7.tif'
outfile = '/iPythonData/cstone/prec_result.tif'
expr = 'A<125'
gdal_calc.py -A=a --outfile=outfile --calc='expr' --NoDataValue=0
It keeps coming up with can't assign to operator. Can someone please help with the whole code.
Looking at the source code for gdal_calc.py, the file is only about 300 lines. Here is a link to that file.
https://raw.githubusercontent.com/OSGeo/gdal/trunk/gdal/swig/python/scripts/gdal_calc.py
The punchline is that they just create an OptionParser object in main and pass it to the doit() method (Line 63). You could generate the same OptionParser instance based on the same arguments you pass to it via the command-line and call their doit method directly.
That said, a system call is perfectly valid per #thomas-k. This is only if you really want to stay in the Python environment.

Working with layout object attributes and variables in FileMaker

This is the first time I'm encountering GetLayoutObjectAttribute and I am having serious issues with it. My variable $web won't set. I think it's because PD_WebV isn't the right object name to refer to, but I don't know how to find the right object name. I can't find the objects name when I hit Edit Layout, so does anyone know how to find an layout objects name?
Loop
Pause/Resume Script [Duration (seconds): 1]
Set Variable[$Web; Value: GetLayoutObjectAttribute("PD_WebV";"content")]
If[$Web="done"]
#execute if statements
After Edit:
After some troubleshooting, I found out that PD_WebV is the right object name to refer and it's refered to correctly, so my new question is why doesn't the script go to the line If[$Web="done"] and how could I fix it? Ss my If statement not evaluating something it should be? Is my $web variable never set to done or is the issue something completely different? Would the problem possibly have to do with my WebDirect sharing settings? Any guidance would help. Thanks.
After, After Edit:
So now that my application is getting past Set Variable[$Web; Value: GetLayoutObjectAttribute("PD_WebV";"content")], the variable $web only equals <HTML></HTML>. Does anyone know a way, without using javascript, to test the inside of the html tags?
Also, I printed the bounds of the webViewer PD_WebV that I can't locate on the layout but am referring to in the script. The bounds that are printed are different each time I run the script. Is the usual or unusual? My source is also about:blank so it doesn't look like I'm sourcing from a URL
Is my $web variable never set to done or is the issue something
completely different?
If you're doing:
Set Variable[$Web; Value: GetLayoutObjectAttribute("PD_WebV";"content")]
then the only time
$Web="done"
will return true is when the web page loaded into your web viewer contains exactly the string "done" (in practical terms, that's never).
I have already suggested in a comment that you test for:
PatternCount ( $webpage ; "</html>" )
This is assuming you want the subsequent steps to execute only after the page has finished loading. The entire script would look something like this:
Loop
Pause/Resume Script [Duration (seconds): 1]
Set Variable[$Web; Value: GetLayoutObjectAttribute("PD_WebV";"content")]
Exit Loop If [ PatternCount ( $webpage ; "</html>" ) ]
End Loop
# execute statements
You might also want to add a counter to the loop and exit the script after n trials.
Ah, I reread your question.
To set the object name for your webviewer so that the GetLayoutObjectAttribute function works you need to set it in the Name field in the inspector when you have the webviewer selected.
e.g.:
After that your variable should populate.
Be aware
What it will populate with will be all of the html from the browser, i.e. not a boolean true/false liek your conditional suggests.
I'm not sure exactly what you're trying to accomplish, but to be able to determine a result from your web viewer you'll need to either parse the HTML to see if it's content contains what you're looking for or within the code you're setting the webviewer with, fire a javascript function that calls back to the FileMaker file using a FileMaker url.

Windbg: Creating log of function entry and exit

I wish to create log of function entry and exit for my code. I am using the following command in WinDbg-
Function name and the return value
bm <module_name>!* "kcL1;.echotime;gu;r eax;.echotime;gc;"
Now I wish to do this for all the modules of the function but I don't want to write the code again for each module. Is there some way to specify bm to read module names from a file which I create using "lm" and set breakpoint for each module or something even more simple.
Also, how can I specify bm to not print the output on the screen? I am using a log file.
Sometimes I don't see the time for call exit. What can be the reason for this? How can I correct it?
you can use !for_each_module
You will not see call exit time if another breakpoint is hit (in another thread, or if the funciton calls other functions that have breakpoints)

Import AppleScript methods in another AppleScript?

Is there a way to use defined AppleScript methods in other AppleScripts which reference the original AppleScript with something similar to import (f.e. in PHP)?
I wrote a methode to set Skype status and mood-text:
on setSkypeStatus(status, mood_text)
tell application "System Events"
set skypeRunning to count (every process whose name is "Skype")
if skypeRunning > 0 then --only set status if skype is running
tell application "Skype"
set myStatus to "SET USERSTATUS " & status
set myMood to "SET PROFILE MOOD_TEXT " & mood_text
send command myStatus script name "AppleScript"
send command myMood script name "AppleScript"
return skypeRunning
end tell
else
return skypeRunning
end if
end tell
end setSkypeStatus
now I'm searching for something like import skype_methods.scpt. Is there such a functionality. I can't something related with Google.
One way to import another script as a library is to define a property which is initialized by loading the library as a script object. You can then use the tell command to invoke the library functions.
property pSkypeLibrary : load script POSIX file "/Users/sakra/Desktop/skype_methods.scpt"
tell pSkypeLibrary
setSkypeStatus("status", "mood")
end tell
Script Foo.scpt
set theBar to "path:to:Bar.scpt" as alias
run script (theBar)
Script Bar.scpt
display dialog "Bar"
Result: A window that displays "Bar"
There is a more elegant way of doing this. You can save your skype_methods.scpt file inside a Script Libraries folder on your computer.
Depending on how you want to define the availability of this library, you use a different folder.
Place the skype_methods.scpt file inside the /Library/Script Libraries folder to make it available for all users on the computer.
Place it in the ~/Library/Script Libraries folder to make it available for a specific user only.
You can then use all the handlers in that library as follows:
property Skype : script "skype_methods"
Skype's setSkypeStatus("status","mood")
This prevents the need of numerous tell blocks when using handlers from different libraries.
You can follow this repo https://github.com/abbeycode/AppleScripts which organises its scripts into libraries
Here is an example https://github.com/abbeycode/AppleScripts/blob/master/Scripts/Download%20Chase%20Activity.applescript
property LibLoader : load script file ((path to scripts folder from user domain as text) & "Libraries:Library Loader.scpt")
property TransmissionLib : LibLoader's loadScript("Libraries:Transmission.applescript")
property GrowlLib : LibLoader's loadScript("Libraries:Growl.applescript")
property SafariLib : LibLoader's loadScript("Libraries:Safari.applescript")
property DatesLib : LibLoader's loadScript("Libraries:Dates.applescript")