Problem
You want to know the name of the currently running script.
Solution
To determine the full path and filename of the currently executing script, use this function:
function GetScriptName
{
$myInvocation.ScriptName
}
To determine the name that the user actually typed to invoke your script (for example, in a “Usage” message), use the $myInvocation.InvocationName variable.
Discussion
By placing the $myInvocation.ScriptName statement in a function, we drastically simplify the logic it takes to determine the name of the currently running script. If you don’t want to use a function, you can invoke a script block directly, which also simplifies the logic required to determine the current script’s name:
$scriptName = & { $myInvocation.ScriptName }
Although this is a fairly complex way to get access to the current script’s name, the alternative is a bit more errorprone. If you are in the body of a script, you can directly get the name of the current script by typing:
$myInvocation.Path
If you are in a function or script block, though, you must use:
$myInvocation.ScriptName
Working with the $myInvocation.InvocationName variable is sometimes tricky, as it returns the script name when called directly in the script, but not when called from a function in that script. If you need this information from a function, pass it to the function as a parameter.