Current Script Path

by Aug 5, 2015

In PowerShell 1.0 and 2.0, you needed a lot of weird code to find out the current script location:

# make sure the script is saved and NOT "Untitled"!
 
$invocation = (Get-Variable MyInvocation).Value 
$scriptPath = Split-Path $invocation.MyCommand.Path 
$scriptName = $invocation.MyCommand.Name

$scriptPath
$scriptName 

The code would work only if you placed it into the root of your script.

Beginning with PowerShell 3.0, things are much easier, and these special variables are available anywhere in your script:

# make sure the script is saved and NOT "Untitled"!
 
$ScriptName = Split-Path $PSCommandPath -Leaf
$PSScriptRoot
$PSCommandPath
$ScriptName 

Twitter This Tip! ReTweet this Tip!