看起来 PowerShell 闭包不会捕获函数的定义:
PS C:\> function x() { Write-Host 'original x' }
PS C:\> function x-caller-generator() { return { Write-host 'Calling x!'; x }.GetNewClosure() }
PS C:\> $y = x-caller-generator
PS C:\> & $y
Calling x!
original x
PS C:\> function x() { Write-Host 'new x' }
PS C:\> & $y
Calling x!
new x
有没有办法捕获函数的定义?
我实际上遇到的问题是,我创建了一个闭包,但当我的闭包被执行时,函数在某种程度上超出了作用域。(这是构建脚本模块psake正在做的一些奇怪的事情。) 就像这样:
PS C:\> function closure-maker () {
>> function x() { Write-Host 'x!' }
>>
>> return { Write-host 'Calling x'; x }.GetNewClosure()
>> }
>>
PS C:\> $y = closure-maker
PS C:\> & $y
Calling x
The term 'x' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:3 char:39
+ return { Write-host 'Calling x'; x <<<< }.GetNewClosure()
+ CategoryInfo : ObjectNotFound: (x:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
注意:本文使用的是PowerShell 2.0版本,但如果有新内容,我会考虑3.0版本的答案。