显式传递参数
您可以使用and变量传递-WhatIfand-Confirm参数。以下示例通过参数 splatting实现了这一点:$WhatIfPreference$ConfirmPreference
if($ConfirmPreference -eq 'Low') {$conf = @{Confirm = $true}}
StopService MyService -WhatIf:([bool]$WhatIfPreference.IsPresent) @conf
$WhatIfPreference.IsPresentTrue如果在-WhatIf包含功能上使用开关,将是。使用-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在确认首选项为“低”时设置开关。