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:
1 |
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] |
Next, to support -WhatIf
I have to do something like this:
1 2 3 |
if ($PSCmdlet.ShouldProcess("The Target", "The Action")) { ... } |
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:
1 |
What if: Performing the operation "The Action" on target "The Target" |
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:
1 2 3 4 |
Confirm Are you sure you want to perform this action? Performing the operation "The Action" on target "The Target". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): |
Nice!
For only confirmations but no WhatIf one can also use ShouldContinue:
1 2 3 |
if ($PSCmdlet.Continue("The Target", "The Action")) { ... } |
For more details also check out this exhaustive blog post. Even Microsoft docs point to it! Also this for another example.