测试脚本:
function outer
{
[cmdletbinding(supportsshouldprocess=$true)]
param($s)
process
{
$pscmdlet.shouldprocess("outer $s", "ShouldProcess") | out-null
"" | out-file "outer $s"
inner ImplicitPassthru
inner VerbosePassthru -Verbose:$Verbose
inner WhatifPassthru -WhatIf:$WhatIf
}
}
function inner
{
[cmdletbinding(supportsshouldprocess=$true)]
param($s)
process
{
$pscmdlet.shouldprocess("inner $s", "ShouldProcess") | out-null
"" | out-file "inner $s"
}
}
"`n** NORMAL **"
outer normal
"`n** VERBOSE **"
outer verbose -Verbose
"`n** WHATIF **"
outer whatif -WhatIf
输出:
** NORMAL **
VERBOSE: Performing operation "ShouldProcess" on Target "inner VerbosePassthru".
What if: Performing operation "ShouldProcess" on Target "inner WhatifPassthru".
What if: Performing operation "Output to File" on Target "inner WhatifPassthru".
** VERBOSE **
VERBOSE: Performing operation "ShouldProcess" on Target "outer verbose".
VERBOSE: Performing operation "ShouldProcess" on Target "inner VerbosePassthru".
What if: Performing operation "ShouldProcess" on Target "inner WhatifPassthru".
What if: Performing operation "Output to File" on Target "inner WhatifPassthru".
** WHATIF **
What if: Performing operation "ShouldProcess" on Target "outer whatif".
What if: Performing operation "Output to File" on Target "outer whatif".
What if: Performing operation "ShouldProcess" on Target "inner ImplicitPassthru".
What if: Performing operation "Output to File" on Target "inner ImplicitPassthru".
What if: Performing operation "ShouldProcess" on Target "inner VerbosePassthru".
What if: Performing operation "Output to File" on Target "inner VerbosePassthru".
What if: Performing operation "ShouldProcess" on Target "inner WhatifPassthru".
What if: Performing operation "Output to File" on Target "inner WhatifPassthru".
在我看来,这里有几个奇怪的地方:
- 指定 -WhatIf:$foo 将始终在被调用者(及其被调用者)中打开 $WhatIf,无论 $foo 是什么。
- 当您指定 -WhatIf “for real”(不将其限制为现有变量)时,它会隐式传播到被调用者。无需通过或飞溅。
- 与 -WhatIf 不同,显式 -Verbose 不会隐式级联到被调用者。
- 当您尝试手动通过 -Verbose:$foo 时,您确实看到行为类似于 -WhatIf:$foo。但它只影响手动测试 $psCmdlet.ShouldProcess() 的脚本——内置 cmdlet 不受影响。
注意:Confirm 的行为与 WhatIf 相同。为简洁起见,我省略了它。
搜索网络和连接,我几乎看不到任何关于与高级功能有关的 ShouldProcess 行为(赞成或反对)的深入讨论。最接近的是James O'Neill 的一篇文章,它建议在整个调用堆栈中传递一个 $psCmdlet 实例。然而,他这样做是为了解决一个完全不同的问题(避免多次 -Confirm 提示)。同时,当您坚持使用为每个函数提供的标准 $psCmdlet 时,我看不到有关预期结果的文档……更不用说设计模式、最佳实践等……