我最近发现 Powershell 函数只是命名为脚本块。例如
function HelloWorld {
Write-Output "Hello world"
}
$hw = $function:HelloWorld
& $hw
将执行 HelloWorld 方法。
但是,我无法弄清楚的是如何获取对名称中带有破折号的方法的引用:
function Hello-World {
Write-Output "Hello world"
}
$hw = $function:Hello-World
You must provide a value expression on the right-hand side of the '-' operator.
At line:1 char:27
+ $hw = $function:Hello- <<<< World
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedValueExpression
有任何想法吗?
我知道我可以这样做:
$hw = (Get-Item function:Hello-World).ScriptBlock
但它有点“嘈杂”,我喜欢 $function 语法
最佳答案
哦!我应该坚持使用 Programmer Problem Solving Sequence并在我发布到 SO 之前询问了我的同事。看起来我应该使用:
$hw = ${function:Hello-World}
关于powershell - 带破折号的引用命令名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489060/