PowerShell Confirm and WhatIf

Writing a PowerShell script and I wanted to add some -WhatIf capability to it. That’s basically where you can get the -WhatIf option of the PowerShell cmdlets in your own script or function, without making that a parameter.

That statement probably made no sense, so check out this blog post whose problematic implementation patters show what I am talking about. You want to avoid using one of those problematic patterns, and the solution is to ShouldProcess. That post is an amazing read (as are other posts by that author) so I won’t repeat. Suffice to say add the following line to the top of your script to get started:

Next, to support -WhatIf I have to do something like this:

I enclose whatever I want to do that will either be done or not done depending on the -WhatIf switch. And of course I can replace “The Target” and “The Action” with the output from other cmdlets. This will result in output like:

The neat thing is this also gives you the -Confirm switch for free. If I run the script with that switch I will be prompted:

Nice!

For only confirmations but no WhatIf one can also use ShouldContinue:

For more details also check out this exhaustive blog post. Even Microsoft docs point to it! Also this for another example.