For example:
function Foo {
[string]$functionName = commandRetrievesFoo
Write-Host "This function is called $functionName"
}
Output:
PS > Foo
This function is called foo
For example:
function Foo {
[string]$functionName = commandRetrievesFoo
Write-Host "This function is called $functionName"
}
Output:
PS > Foo
This function is called foo
The
Get-PSCallStack
option seems to work only once: when calling a function from the body of the script, the first time it will retrieve the script name, but the second time it will retrieve the text ''When you are in a function you can access the automatic variable $PSCmdLet.
This is an extremely useful variable that holds a lot of information about the currently executing cmdlet.
In our scenario we wanted the name and the definition of the current function for some recursion. $MyInvocation was null because the function was within a PowerShell module.
However, there is a "MyInvocation" property on the PSCmdLet object which contains all the information needed and allowed our scenario to run.
e.g. $PSCmdlet.MyInvocation.MyCommand.Name = The name of the function $PSCmdlet.MyInvocation.MyCommand.Definition = The definition of the function
You can use
$MyInvocation
which contains some useful information about what is currently executed.Easy.
By default Get-FunctionName in the example will get the name of the function that called it.
Increasing the StackNumber parameter will get the name of the next function call up.