我是 Powershell 初学者,虽然不是编程 n00b。我正在尝试创建一个 IDisposable/RAII 风格的故障安全模式,有点像:
http://www.sbrickey.com/Tech/Blog/Post/IDisposable_in_PowerShell
所以我有:
Function global:FailSafeGuard
{
param (
[parameter(Mandatory=$true)] [ScriptBlock] $execute,
[parameter(Mandatory=$true)] [ScriptBlock] $cleanup
)
Try { &$execute }
Finally { &$cleanup }
}
我正在尝试使用它在不同的目录中执行一堆任务,在输入时使用 Push-Location,在输出时使用 Pop-Location。所以我有:
Function global:Push-Location-FailSafe
{
param (
$location,
[ScriptBlock] $execute
)
FailSafeGuard {
Push-Location $location;
&$execute
} { Pop-Location }
}
我发现 Push-Location-FailSafe 中的 $execute 参数与 FailSafe 函数中的 $execute 参数冲突。
Push-Location-FailSafe "C:\" {dir}
The expression after '&' in a pipeline element produced an invalid object. It must result in a command name, script block or CommandInfo object.
At C:\TEMP\b807445c-1738-49ff-8109-18db972ab9e4.ps1:line:20 char:10
+ &$ <<<< execute
我认为这是名称冲突的原因是,如果我在 Push-Location-FailSafe 中将 $execute 重命名为 $execute2,它可以正常工作:
Push-Location-FailSafe "C:\" {dir}
Directory: C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2011-08-18 21:34 cygwin
d---- 2011-08-17 01:46 Dell
[snip]
我对参数的理解有什么问题?