Jason Jarrett
Jason Jarrett

Reputation: 3987

How to get the currently executing file within powershell function

The following S.O. question addresses the problem (when you're trying to figure it out from within a script). How can I get the current PowerShell executing file?

How would you do it if you were within a function.

The Example below works outside the definition of the function, just not inside.

echo ''
echo '******** outside function scope'
echo "Path: $($MyInvocation.MyCommand.Path)"
echo "Definition: $($MyInvocation.MyCommand.Definition)"
echo '*******************************'
echo ''

function myHelper()
{
    echo '******** inside function scope'
    #EMPTY
    echo "Path: $($MyInvocation.MyCommand.Path)"
    #Prints the string definition of the function itself
    echo "Definition: $($MyInvocation.MyCommand.Definition)"
    echo '******************************'
}

myHelper

Upvotes: 3

Views: 1527

Answers (1)

Keith Hill
Keith Hill

Reputation: 201622

You can get this info via:

$MyInvocation.ScriptName

This will return whichever script file the function was invoked from.

Upvotes: 4

Related Questions