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)
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)
使用函数时,可以访问自动变量$ PSCmdLet。
这是一个非常有用的变量,它包含有关当前正在执行的cmdlet的许多信息。
在我们的场景中,我们需要一些递归的名称和当前函数的定义。$ MyInvocation为空,因为该函数在PowerShell模块内。
但是,PSCmdLet对象上有一个“ MyInvocation”属性,其中包含所有需要的信息并允许我们的方案运行。
例如$ PSCmdlet.MyInvocation.MyCommand.Name =函数的名称$ PSCmdlet.MyInvocation.MyCommand.Definition =函数的定义