To start with let’s talk about what ShouldProcess does and look at a basic use case. By adding the “SupportsShouldProcess” to the CmdletBinding attribute and adding the $PSCmdlet.ShouldProcess function call we allow the function to know when a “risky” action is taking place. Here’s a sample function that includes a should process. I’ll break down the parts after the jump.

First let’s look at the CmdletBinding attribute. There are two parts. The SupportsShouldProcess tells us that the function is eligible for prompting. Just that alone wouldn’t do anything, we need to have the ShouldProcess function call below but more on that later.

The second part is ConfirmImpact = ‘High’. When you add SupportsShouldProcess to a function you get access to a few special variables called Preference Variables. In short they are variables that keep track of some of the common parameters that can be passed to a function with a CmdletBinding. In this case we are interested in $ConfirmPreference which can be modified on it’s own or by the ConfirmImpact setter in CmdletBinding. When a function is called that supports should process the $ConfirmPreference is checked. If it’s ‘High’ then the user is always prompted. If the $ConfirmPreference is low then the caller is only prompted if the -Confirm flag is set (one small note for those who care, technically the -Confirm doesn’t modify the $ConfirmPreference but it has the same effect as setting ConfirmImpact to ‘High’)

So in the above example since the ConfirmImpact is set to ‘High’ we will always prompt the user to ask if they want to take action. I set it to ‘High’ in any write function I make because I want it to be impossible for someone to write a new script using that function and accidentally forget the -Confirm. That prompt looks like this:

There’s another common parameter you get access to by adding should process: -WhatIf. If the WhatIf switch is set then the ShouldProcess function is not run and automatically returns $false. This let’s us test out what a function would have done. More on leveraging this for better test-ability later on. For now just consider it a way to test out a function without any side effects.