views:

48

answers:

1

Is there a way to retrieve a function name from within a function.

for example:

function foo { [string]$functionName = commnandRetrievesFoo Write-Host "This function is called $functionName" }

PS > This function is called foo

+1  A: 

You can use $MyInvocation which contains some useful information about what is currently executed.

function foo {
    'This function is called {0}.' -f $MyInvocation.MyCommand
}
Joey
That works - thanks any idea how to get the calling function name? I tried other $myInvocation properties but I don't see one. function foo { 'This function is called {0}.' -f $MyInvocation.MyCommand 'This Caller is called {0}.' -f $MyInvocation.? }function CallFoo { foo }CallFoo
alphadev
If you are on PowerShell 2.0 use `(Get-PSCallStack)[1].Command`.
Keith Hill
Make that a separate question, so people can find it. The answer in v1 is in `gv -sc $_ myinvocation`. See http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!172.entry
Jay Bazuzi