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

FunctionPowershell

Function Problem Overview


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?

Function Solutions


Solution 1 - Function

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.

Solution 2 - Function

In your worker file, dot-source the library file, this will load all content (functions, variables, etc) to the global scope, and then you'll be able to call functions from the library file.

=================== Worker file ==========================
# dot-source library script
# notice that you need to have a space 
# between the dot and the path of the script
. c:\library.ps1

ShowMessage -AValue Hello
=================== End Worker file ======================

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian FrostView Question on Stackoverflow
Solution 1 - FunctionAndrey MarchukView Answer on Stackoverflow
Solution 2 - FunctionShay LevyView Answer on Stackoverflow