About | Links | Scripts
Sharing linux/windows scripts and tips

The correct way to implement -Whatif and -Confirm in a Powershell Cmdlet

January 08, 2019 — Jesse Harris

When I first learned about [CmdLetBinding()] to add automatic support for Write-Verbose I didn't understand why -WhatIf and -Confirm were not passed to Cmdlets used in my functions.

I wrote functions like this to fake it:

    function Set-BadIdea {

        Remove-Item $File -WhatIf:$WhatIf -Confirm:$Confirm


While this kinda works, it doesn't allow any control over where Whatif's and confirms are used. After reading Implementing ShouldProccess for your functions post by Joel Francsis, I'm now able to do things like this:

    function Set-GoodIdead {

        If ($PSCmdlet.ShouldProcess("$File", "Get rid of junk")) {
            Remove-Item $File 


As I hope you can see, you could implement the $PSCmdlet.ShouldProcess on any code, not just other functions that support -WhatIf or -Confirm or -Force

Doing this will lead to more consistent behavior of functions and allow behaviour to be more intuitive.

For a much more in depth explaination, go and check Joel's post

Tags: powershell, coding