PowerShell: get the current script path and name
Comparison of $PSCommandPath and the $MyInvocation properties, in a script and inside a function.
Finding the name or path of the running script is a common source of confusion: the $PSScriptRoot and $PSCommandPath automatic variables, and the PSScriptRoot and PSCommandPath properties of $MyInvocation, describe the invoker (the caller) rather than always the current script. This article compares the variants, directly in the script and inside a function (see also the Stack Overflow discussion).
Test script
function PSCommandPath() { return $PSCommandPath; }
function ScriptName() { return $MyInvocation.ScriptName; }
function MyCommandName() { return $MyInvocation.MyCommand.Name; }
function MyCommandDefinition() { return $MyInvocation.MyCommand.Definition; }
function MyInvocationPSCommandPath() { return $MyInvocation.PSCommandPath; }
Write-Host "PSVersion: $($PSVersionTable.PSVersion)"
Write-Host "`$PSCommandPath:"
Write-Host " * Direct: $PSCommandPath"
Write-Host " * Function: $(PSCommandPath)"
Write-Host "`$MyInvocation.ScriptName:"
Write-Host " * Direct: $($MyInvocation.ScriptName)"
Write-Host " * Function: $(ScriptName)"
Write-Host "`$MyInvocation.MyCommand.Name:"
Write-Host " * Direct: $($MyInvocation.MyCommand.Name)"
Write-Host " * Function: $(MyCommandName)"
Write-Host "`$MyInvocation.MyCommand.Definition:"
Write-Host " * Direct: $($MyInvocation.MyCommand.Definition)"
Write-Host " * Function: $(MyCommandDefinition)"
Write-Host "`$MyInvocation.PSCommandPath:"
Write-Host " * Direct: $($MyInvocation.PSCommandPath)"
Write-Host " * Function: $(MyInvocationPSCommandPath)"
Result (script C:\Test\test.ps1, PowerShell 5.1)
| Variable | Directly in the script | Inside a function |
|---|---|---|
$PSCommandPath |
C:\Test\test.ps1 |
C:\Test\test.ps1 |
$MyInvocation.ScriptName |
empty | C:\Test\test.ps1 |
$MyInvocation.MyCommand.Name |
test.ps1 |
function name |
$MyInvocation.MyCommand.Definition |
C:\Test\test.ps1 |
function body |
$MyInvocation.PSCommandPath |
empty | C:\Test\test.ps1 |
Notes
$PSCommandPathis the simplest solution: it returns the full path of the current script, both directly and from inside a function.$MyInvocation.MyCommand.Definitioninside a function returns the function's contents, not a path.