$ cat "

Using Paths Relative to Script File Directory in PowerShell

"

If you are not careful, using paths in PowerShell scripts have a tendency to make your script brittle:

  • Absolute paths: The script probably fails when executed on a different machine
  • Relative paths: The script fails if executed with a different working directory


To remedy this there is a magical and wonderful variable in PowerShell called $PSScriptRoot (in PowerShell 3+), which contains the path to the current script file. By using this you know that you can safely access files relative to the actual script file, no matter the working directory, and without having to hard code any absolute paths into the script.

For example:

Get-ChildItem $PSScriptRoot\some\directory

If you are stuck on PowerShell 2 or below, you can use the following snippet instead, to get the same behaviour:

$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
Written by Erik Öjebo 2015-10-08 21:11

    Comments