Powershell 函数参考和命名约定
Powershell function reference and naming conventions
最近发现可以通过修饰符$function:
引用获取powershell的函数。但是我注意到一个奇怪的问题...
按照惯例,POSH 使用 {Verb}-{Noun}
函数名称约定,其中 {Verb}
是 aproved POSH verb names 的一部分。例如:Get-Member
或 Invoke-WebRequest
.
问题是,例如调用 $function:Get-Member
是无效的,因为有连字符;如果您声明一个像 ShowMessage
的函数并调用:$fn = $function:ShowMessage
,它就可以正常工作。所以我想知道是否有办法逃避这个电话。
PS.: 我知道另一种选择,但要冗长得多:
function Show-Message { Write-Host "Foo"; }
$fn = (Get-Item "function:Show-Message").ScriptBlock;
$fn.Invoke();
更新: 尽管@PetSerAl 非常有帮助并解释了问题,但我会将@Ansgar Wiechers 的回复标记为答案,因为它有更好的记录。
function:
是 PSDrive,不是(范围)修饰符。至于使用类似变量的表示法($function:name
):具有特殊字符的变量名规则也适用于此。
VARIABLE NAMES THAT INCLUDE SPECIAL CHARACTERS
Variable names begin with a dollar sign. They can include alphanumeric characters and special characters. The length of the variable name is limited only by available memory.
Whenever possible, variable names should include only alphanumeric characters and the underscore character (_).Variable names that include spaces and other special characters, are difficult to use and should be avoided.
To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs PowerShell to interpret the characters in the variable name literally.
因此您的符号应如下所示:
${function:Show-Message}
可以这样调用:
& ${function:Show-Message}
最近发现可以通过修饰符$function:
引用获取powershell的函数。但是我注意到一个奇怪的问题...
按照惯例,POSH 使用 {Verb}-{Noun}
函数名称约定,其中 {Verb}
是 aproved POSH verb names 的一部分。例如:Get-Member
或 Invoke-WebRequest
.
问题是,例如调用 $function:Get-Member
是无效的,因为有连字符;如果您声明一个像 ShowMessage
的函数并调用:$fn = $function:ShowMessage
,它就可以正常工作。所以我想知道是否有办法逃避这个电话。
PS.: 我知道另一种选择,但要冗长得多:
function Show-Message { Write-Host "Foo"; }
$fn = (Get-Item "function:Show-Message").ScriptBlock;
$fn.Invoke();
更新: 尽管@PetSerAl 非常有帮助并解释了问题,但我会将@Ansgar Wiechers 的回复标记为答案,因为它有更好的记录。
function:
是 PSDrive,不是(范围)修饰符。至于使用类似变量的表示法($function:name
):具有特殊字符的变量名规则也适用于此。
VARIABLE NAMES THAT INCLUDE SPECIAL CHARACTERS
Variable names begin with a dollar sign. They can include alphanumeric characters and special characters. The length of the variable name is limited only by available memory.
Whenever possible, variable names should include only alphanumeric characters and the underscore character (_).Variable names that include spaces and other special characters, are difficult to use and should be avoided.
To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs PowerShell to interpret the characters in the variable name literally.
因此您的符号应如下所示:
${function:Show-Message}
可以这样调用:
& ${function:Show-Message}