I’ve previously needed to get the name of the PowerShell script that’s running from within the script itself. I came across this solution, but today ran into a scenario where that doesn’t work.
This will work, unless it’s being called from within a function – in which case it will return the function’s name instead:
$scriptName = $MyInvocation.MyCommand.Name
I needed to get the calling script’s name from within a logging function in one of my scripts, so I ended up doing this:
$scriptName = $MyInvocation.ScriptName.Replace((Split-Path $MyInvocation.ScriptName),'').TrimStart('')