Loading Functions from Separate File

by Jul 15, 2014

PowerShell 3.0 and newer

To keep things simple, you may want to put PowerShell functions into a separate file. To load these functions into your job scripts, you can use a simple approach.

Make sure the script file with your PowerShell functions is stored in the same folder with your job script. Then, your job script uses this simple line:

. "$PSScriptRoot\library1.ps1"

This line would load a script called “library1.ps1” from the folder the current script is stored in. Do not forget the dot and space at the beginning: “dot-sourcing” a file ensures that all of its variables and functions are defined in the caller context and not cleaned up after the script executed.

Note that $PSScriptRoot always contains the path to the folder a script is stored in (starting in PowerShell 3.0). Make sure to actually save your script because only saved scripts will have a parent folder.

Twitter This Tip! ReTweet this Tip!