Including Resources with Your Scripts

by Mar 24, 2015

PowerShell 3.0 and later

If your script needs additional resources, like text lists of server names, or picture files, or anything else, then make sure your script stays portable.

Never use absolute path names to refer to your resource files. Instead, make use of $PSScriptRoot which was introduced in PowerShell 3.0 (in PowerShell 2.0, $PSScriptRoot was available for modules only).

$picture = "$PSScriptRoot\Resources\picture.png"
Test-Path -Path $picture

$data = "$PSScriptRoot\Resources\somedata.txt"
Get-Content -Path $data

$PSScriptRoot always contains the path name to the folder where your script is currently stored. (which is why this variable is empty if you never saved your script or queried this variable interactively).

Twitter This Tip! ReTweet this Tip!