Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function in another script when executing using 'Run With PowerShell'

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?

like image 370
Brian Frost Avatar asked Dec 14 '11 08:12

Brian Frost


People also ask

How do you call function in a script to another script in PowerShell?

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.

How do you call another function in PowerShell?

To call another function, you need to use the Invoke-Command cmdlet and pass in the argument using the ArgumentList parameter like below.

How do you call a parameterized function in PowerShell?

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.

Can you nest functions in PowerShell?

In Windows PowerShell® Workflow, you can include functions and nested workflows to reuse and organize the commands in a script workflow.


1 Answers

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.

like image 52
Andrey Marchuk Avatar answered Sep 27 '22 21:09

Andrey Marchuk