Use $PSScriptRoot to Load Resources

by Feb 20, 2014

Beginning in PowerShell 3.0, there is a new automatic variable available called $PSScriptRoot. This variable previously was only available within modules. It always points to the folder the current script is located in (so it only starts to be useful once you actually save a script before you run it).

You can use $PSScriptRoot to load additional resources relative to your script location. For example, if you decide to place some functions in a separate "library" script that is located in the same folder, this would load the library script and import all of its functions:

# this loads the script "library1.ps1" if it is located in the very
# same folder as this script.
# Requires PowerShell 3.0 or better.

. "$PSScriptRoot\library1.ps1" 

Likewise, if you would rather want to store your library scripts in a subfolder, try this (assuming the library scripts have been placed in a folder called "resources" that resides in the same folder as your script:

# this loads the script "library1.ps1" if it is located in the subfolder
# "resources" in the folder this script is in.
# Requires PowerShell 3.0 or better.

. "$PSScriptRoot\resources\library1.ps1" 

Twitter This Tip! ReTweet this Tip!