如何将函数保存到变量中?
function sayHello {
write-host Hello, world!
}
$a = sayHello
然后,我想致电$a
。
另一个例子:
$a = get-childItem
$a -name
答案 0 :(得分:8)
您可以使用function
变量范围限定符来引用函数定义本身:
$helloFunc = $function:sayHello
现在您可以使用调用运算符(&
)调用它:
& $helloFunc
呼叫操作员也支持参数:
PS C:\> function test-param {param($a,$b) $b,$a |Write-Host}
PS C:\> $tp = ${function:test-param}
PS C:\> & $tp 123 456
456
123
PS C:\> & $tp -b 123 -a 456
123
456