The following variables exist in PowerShell 5.1+, both of which seem to offer the full path to the ‘invoking’ script (i.e. the script that called this one, e.g. from a module, a function, or an external script):
$MyInvocation.ScriptName
$MyInvocation.PSCommandPath
I can find official documentation referencing both as options:
…[$MyInvocation.]ScriptName refers to the name of the script that called you (Yes –
we probably should have chosen a better name)
[$MyInvocation.]PSCommandPath contains the full path and name of the script that
called or invoked the current script.
Which one should I use? My current theories & observations:
- $MyInvocation.ScriptName may be available in older versions (based on the sample output in 1), whereas $MyInvocation.PSCommandPath may be a newer addition (to offer more consistency compared with $PSCommandPath?
- $MyInvocation.ScriptName returns ” (empty string) when there is no calling script, whereas $MyInvocation.PSCommandPath does not (in my testing, it returns $null)
Any other weird edge-cases or hidden ‘gotchas’ with either of these that I should be aware of? Or should I be aware of any situations where one should be preferred over the other?