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 答案感兴趣。