Skip to main content
 首页 » 编程设计

powershell之如何在调用其他 Cmdlet 的 Cmdlet 中支持 PowerShell 的 -WhatIf & -Confirm 参数

2025年02月15日31kerrycode

我有一个支持 -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开启包含功能临时设置 $ConfirmPreferencelow .

隐式传递参数

-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如果确认首选项为“低”,则切换。