简体   繁体   中英

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

For example:

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

Output:

PS > Foo
This function is called foo

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

function foo {
    'This function is called {0}.' -f $MyInvocation.MyCommand
}

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.

eg $PSCmdlet.MyInvocation.MyCommand.Name = The name of the function $PSCmdlet.MyInvocation.MyCommand.Definition = The definition of the function

Get-PSCallStack选项似乎只工作一次:当从脚本体调用函数时,它第一次检索脚本名称,但第二次它将检索文本''

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM