How do you support PowerShell's -WhatIf & -Confirm parameters in a Cmdlet that calls other Cmdlets?

后端 未结 4 463
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 01:42

I have a PowerShell script cmdlet that supports the -WhatIf & -Confirm parameters.

It does this by calling the $PSCmdlet.Should

4条回答
  •  悲哀的现实
    2020-12-14 02:14

    Updated per @manojlds comment

    Cast $WhatIf and $Confirm to Boolean and pass the values to the the underlying cmdlet:

    function Stop-CompanyXyzServices
    {
        [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='High')]
    
        Param(
            [Parameter(
                Position=0,
                ValueFromPipeline=$true,
                ValueFromPipelineByPropertyName=$true
            )]      
            [string]$Name
        )
    
    
        process
        {
            if($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Stop service '$Name'"))
            {                   
                Stop-Service $name -WhatIf:([bool]$WhatIf) -Confirm:([bool]$confirm)
            }                       
        }
    }
    

提交回复
热议问题