59

I've got some additional functions that I've defined in an additional PowerShell script file, that I'm trying to load in a main .ps1 file. However, when I call the .ps1 file from the PowerShell prompt it doesn't seem to run through those commands.

In the following code example, build_functions.ps1 has code that defines various custom functions. If I run the file separately (for example, running it by itself and then running through the primary script) it works fine. Build_builddefs.ps1 contains a number of variables that also need to be populated prior to running the primary script.

At the beginning of my primary script I have this:

.\build_functions.ps1
.\build_builddefs.ps1

However, these don't seem to be run, because the primary script fails when it tries to execute the first custom function. What am I doing wrong?

1

4 Answers 4

74

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

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

3 Comments

If I do not know the source path, how can I find out?
@Timo check my answer ;)
Also, you can run dir function: after that to make sure the function got loaded.
46

I kept using this all this time

Import-module .\build_functions.ps1 -Force

2 Comments

I prefer this answer to @manojlds because dot sourcing doesn't allow a user to "undo" the dot sourcing. With Import-Module you can easily remove the module by Remove-Module Build_Functions
It's best to avoid using Import-Module with regular .ps1 scripts (as opposed to .psm1 files, which are true modules), because it can create conceptual confusion. In effect, Import-module .\build_functions.ps1 -Force is the same as . .\build_functions.ps1 - simple dot-sourcing, no actual modules involved (except for a pseudo module showing up in Get-Module output). Therefore, @FrankFu, you can not use Remove-Module to unload such definitions later - see this answer for details.
2

KERR's answer is IMO the only "valid" one. Relative paths given like in most answers won't resolve from the script's path but from PWD...

Here is how to load relative files:

$parent_dir = Split-Path $MyInvocation.MyCommand.Path

. $parent_dir\Scripts\prompt.ps1
. $parent_dir\Scripts\aliases.ps1
. $parent_dir\Scripts\isoTools.ps1

You can find more informations about Automatic Variable here

Comments

0

Here's how to load one from a specific path/directory:

. "C:\scripts\Function-Search-AD.ps1"

enter image description here

Comments

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.