Is there a way to retrieve a PowerShell function name from within a function?

Viewed 27293

For example:

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

Output:

PS > Foo
This function is called foo
4 Answers

Easy.

function Get-FunctionName ([int]$StackNumber = 1) {
    return [string]$(Get-PSCallStack)[$StackNumber].FunctionName
}

By default Get-FunctionName in the example will get the name of the function that called it.

Function get-foo () {
    Get-FunctionName
}
get-foo
#Reutrns 'get-foo'

Increasing the StackNumber parameter will get the name of the next function call up.

Function get-foo () {
    Get-FunctionName -StackNumber 2
}
Function get-Bar  () {
    get-foo 
}
get-Bar 
#Reutrns 'get-Bar'
Related