62

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?

1
  • 1
    Also note that invoking the script using &, eg. & "c:\scratch\b.ps1" doesn't import the functions. Commented Aug 10, 2017 at 21:57

2 Answers 2

104

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Attention when using relative pathing: Don't forget to prepend a dot before the path . ".\b.ps1". Being very new to psh, I didn't know that the first dot is an operator to modify the scope and in that context has nothing to do with paths. See Dot Source Notation.
@RoiDanton you're great Roi... thanks for adding this comment... this is what I was searching for, that is, how to call a function from another script that's inside the same folder\path using relative path.
The relative pathing not working for me. I'm using PowerShell 5.1, does this have anything to do with it?
19

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 ======================

5 Comments

It's safer to enclose path in quotes, in case there will be space, like Program Files
Agree, but this path has no spaces :). I tend to remove quotes when they are not necessary.
Good answer, but it's the current scope that "dot-sourcing" a file causes it to run in, which may or may not be the global scope.
@mklement0 How do you know/set the scope there?
@mklement0 Sorry, I found out you can set the [global, local] scope of the functions using: function global:myfunction {..}. For more info use: Get-Help about_Scopes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.