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

后端 未结 4 449
隐瞒了意图╮
隐瞒了意图╮ 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:21

    Here is a complete solution based on @Rynant and @Shay Levy's answers:

    function Stop-CompanyXyzServices
    {
        [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
    
        Param(
            [Parameter(
                Position=0,
                ValueFromPipeline=$true,
                ValueFromPipelineByPropertyName=$true
            )]      
            [string]$Name
        )
    
        process
        {
            if($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Stop XYZ services '$Name'")){  
                ActualCmdletProcess
            }
            if([bool]$WhatIfPreference.IsPresent){
                ActualCmdletProcess
            }
        }
    }
    
    function ActualCmdletProcess{
    # add here the actual logic of your cmdlet, and any call to other cmdlets
    Stop-Service $name -WhatIf:([bool]$WhatIfPreference.IsPresent) -Confirm:("Low","Medium" -contains $ConfirmPreference)
    }
    

    We have to see if -WhatIf is passed separately as well so that the whatif can be passed on to the individual cmdlets. ActualCmdletProcess is basically a refactoring so that you don't call the same set of commands again just for the WhatIf. Hope this helps someone.

提交回复
热议问题