Powershell 用破折号引用命令名
我最近发现Powershell函数只是命名为ScriptBlock。比如说Powershell 用破折号引用命令名,powershell,powershell-2.0,Powershell,Powershell 2.0,我最近发现Powershell函数只是命名为ScriptBlock。比如说 function HelloWorld { Write-Output "Hello world" } $hw = $function:HelloWorld & $hw 将执行HelloWorld方法 但是,我还没有弄清楚的是,如何获取对名称中有破折号的方法的引用: function Hello-World { Write-Output "Hello world" } $hw =
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
但是它有点“嘈杂”,我喜欢$function语法!我应该坚持下去,在我发邮件到SO之前问我的同事。看起来我应该使用:
$hw = ${function:Hello-World}
要调用该函数,只需按其名称调用即可
PS> Hello-World
Hello world
${function:Hello World}
是获取函数代码的方法。还有一种方法:
Get-Command Hello-World | Select-Object -ExpandProperty Definition
除了使用
$script=${function:hello world}
还有$script=get content function:hello world
“$”一元运算符等于使用get content
(别名是gc
)Ah!这是一个很好的关于“$”的因素。。我觉得我所有的脚本很快就会像jQuery了@x0n这对我不起作用。执行${function:Get Item}不会给出任何结果。这可能是因为Get Item是一个commandlet,而x0n谈论的是函数引用吗?正确-Get Item是一个二进制cmdlet。它在功能驱动上不符合逻辑。这对我不起作用。执行${function:Get Item}不会给出任何结果
Get-Command Hello-World | Select-Object -ExpandProperty Definition