I have functions in a 'library' file to be called from my 'worker' script.
Library File
function ShowMessage($AValue) { $a = new-object -comobject wscript.shell $b = $a.popup( $AValue ) }
Worker File
. {c:\scratch\b.ps1} ShowMessage "Hello"
Running the 'worker' script works fine when in the PowerShell IDE but when I right-click the worker file and choose 'Run with PowerShell' it cannot find the function 'ShowMessage'. Both files are in the same folder. What might be happening?
You can write an entire library of functions and save each to a separate file, then use dot-sourcing to call them from a script. You could even go a step further and dot-source the functions into your PowerShell profile to make them available every time you launch PowerShell.
To call another function, you need to use the Invoke-Command cmdlet and pass in the argument using the ArgumentList parameter like below.
You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.
In Windows PowerShell® Workflow, you can include functions and nested workflows to reuse and organize the commands in a script workflow.
In the worker file change to this:
. "c:\scratch\b.ps1" ShowMessage "Hello"
As @RoiDanton mentioned below:
Attention when using relative pathing: Don't forget to prepend a dot before the path . ".\b.ps1".
The first dot is an operator used to modify the scope and in that context it has nothing to do with paths. See Dot Source Notation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With