A colleague of mine was writing a cool function that tidies up the GPOs, and he wanted to implement the -WhatIf common cmdlet parameter in his function.

There’s a simple way of doing that, just add the [cmdletBinding(SupportsShouldProcess)] and the param() blocks in the top of your function, add the if ($PSCmdlet.ShouldProcess($target)) {} in the body. Where the scriptblock is where you put all your function logic. For example:

function Do-Something {
    [cmdletbinding(SupportsShouldProcess)]
    Param()
    $target = Get-Something
    if ($PSCmdlet.ShouldProcess($target)) {
        Set-Something -Target $target
        Set-AnotherThing -Target $target
    }
}

Then, if you call it with the -WhatIf or -Confirm switches, the output would be:


PS> Do-Something -WhatIf
What if: Performing the operation "Do-Something" on target "'Target'".

PS> Do-Something -Confirm
Confirm
Are you sure you want to perform this action?
Performing the operation "Do-Something" on target "'Target'".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

But he wanted the WhatIf message or confirmation for each of the operations he was doing inside his function, not just one.

So instead of using the “plain” if ($PSCmdlet.ShouldProcess($target)) {}, I suggested he used a hashtable to “splat” the values of -WhatIf and -Confirm “down” to the cmdlets in his function. For example:

function Do-Something {
    [cmdletbinding(SupportsShouldProcess)]
    Param()
    $target = Get-Something
    $commonParams = @{}
    if($WhatIfPreference.IsPresent) {$commonParams.Add('WhatIf', $true)}
    if($ConfirmPreference.IsPresent) {$commonParams.Add('Confirm', $true)}
    Set-Something -Target $target @commonParams
    Set-AnotherThing -Target $target @commonParams
}

Then, if you call it with the -WhatIf or -Confirm switches, the output would be:


PS> Do-Something -WhatIf
What if: Performing the operation "Set-Something" on target "'Target'".
What if: Performing the operation "Set-AnotherThing" on target "'Target'".

PS> Do-Something -Confirm
Confirm
Are you sure you want to perform this action?
Performing the operation "Set-Something" on target "'Target'".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

Confirm
Are you sure you want to perform this action?
Performing the operation "Set-AnotherThing" on target "'Target'".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

For more information about the common cmdlet parameters and the risk mitigation switches, run:

Get-Help -Name about_CommonParameters

HTH,
Martin.

Advertisements