我有一个支持 -WhatIf
的 PowerShell 脚本 cmdlet & -Confirm
参数。
它通过调用 $PSCmdlet.ShouldProcess()
来做到这一点。执行更改之前的方法。
这按预期工作。
我遇到的问题是我的 Cmdlet 是通过调用其他 Cmdlet 和 -WhatIf
来实现的。或 -Confirm
参数不会传递给我调用的 Cmdlet。
如何传递 -WhatIf
的值和 -Confirm
到我从 Cmdlet 调用的 Cmdlet?
例如,如果我的 Cmdlet 是 Stop-CompanyXyzServices
它使用 Stop-Service
以实现其行动。
如 -WhatIf
传递给 Stop-CompanyXyzServices
我希望它也被传递给停止服务。
这可能吗?
请您参考如下方法:
显式传递参数
您可以通过 -WhatIf
和 -Confirm
参数与$WhatIfPreference
和 $ConfirmPreference
变量。以下示例使用 parameter splatting 实现了这一点:
if($ConfirmPreference -eq 'Low') {$conf = @{Confirm = $true}}
StopService MyService -WhatIf:([bool]$WhatIfPreference.IsPresent) @conf
$WhatIfPreference.IsPresent
将是
True
如果
-WhatIf
switch 用于包含函数。使用
-Confirm
开启包含功能临时设置
$ConfirmPreference
至
low
.
隐式传递参数
自
-Confirm
和
-WhatIf
临时设置
$ConfirmPreference
和
$WhatIfPreference
自动变量,甚至有必要传递它们吗?
考虑这个例子:
function ShouldTestCallee {
[cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
param($test)
$PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Confirm?")
}
function ShouldTestCaller {
[cmdletBinding(SupportsShouldProcess=$true)]
param($test)
ShouldTestCallee
}
$ConfirmPreference = 'High'
ShouldTestCaller
ShouldTestCaller -Confirm
ShouldTestCaller
结果
True
来自
ShouldProcess()
ShouldTestCaller -Confirm
即使我没有通过开关,也会导致确认提示。
编辑
@manojlds 的回答让我意识到我的解决方案总是设置
$ConfirmPreference
到“低”或“高”。我已更新我的代码以仅设置
-Confirm
如果确认首选项为“低”,则切换。