有没有办法从函数中检索PowerShell函数名?

alp*_*dev 19 reflection powershell function

例如:

function Foo { 
    [string]$functionName = commandRetrievesFoo
    Write-Host "This function is called $functionName"
}
Run Code Online (Sandbox Code Playgroud)

输出:

PS > Foo
This function is called foo
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 31

您可以使用$MyInvocation其中包含有关当前执行内容的一些有用信息.

function foo {
    'This function is called {0}.' -f $MyInvocation.MyCommand
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是PowerShell 2.0,请使用`(Get-PSCallStack)[1] .Command`. (8认同)
  • 把它作为一个单独的问题,以便人们可以找到它.v1的答案在`gv -sc $ _ myinvocation`中.见http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!172.entry (2认同)
  • 我遇到了两种获取调用函数名称的方法:1)`(Get-PSCallStack | Select-Object FunctionName -Skip 1 -First 1).FunctionName`和2)`(Get-Variable MyInvocation -Scope 1)。 Value.MyCommand.Name`。我尝试将每个循环运行1000次,以查看每个循环花费了多长时间。Get-Variable ...方法花费的时间大约是Get-PSCallStack ...方法的一半。 (2认同)
  • `$MyInspiration` 不能用于获取类中函数的名称。为此,我需要使用 `Get-PSCallStack)[0].FunctionName` (2认同)

Jak*_*bii 14

简单的。

function Get-FunctionName ([int]$StackNumber = 1) {
    return [string]$(Get-PSCallStack)[$StackNumber].FunctionName
}
Run Code Online (Sandbox Code Playgroud)

默认情况下,示例中的Get-FunctionName将获取调用它的函数的名称。

Function get-foo () {
    Get-FunctionName
}
get-foo
#Reutrns 'get-foo'
Run Code Online (Sandbox Code Playgroud)

增加StackNumber参数将获取下一个函数调用的名称。

Function get-foo () {
    Get-FunctionName -StackNumber 2
}
Function get-Bar  () {
    get-foo 
}
get-Bar 
#Reutrns 'get-Bar'
Run Code Online (Sandbox Code Playgroud)


Car*_*rlR 6

使用函数时,可以访问自动变量$ PSCmdLet

这是一个非常有用的变量,它包含有关当前正在执行的cmdlet的许多信息。

在我们的场景中,我们需要一些递归的名称和当前函数的定义。$ MyInvocation为空,因为该函数在PowerShell模块内。

但是,PSCmdLet对象上有一个“ MyInvocation”属性,其中包含所有需要的信息并允许我们的方案运行。

例如$ PSCmdlet.MyInvocation.MyCommand.Name =函数的名称$ PSCmdlet.MyInvocation.MyCommand.Definition =函数的定义

  • $PsCmdlet 的 [about_automatic_variables](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-5.1) 条目显示“包含一个表示正在运行的 cmdlet 或高级函数。因此它仅适用于具有 CmdletBindingAttribute 的高级函数,不适用于普通函数。 (3认同)
  • $ PSCmdlet`仅在该函数具有显式的[CmdletBinding()]属性时才起作用。 (2认同)