Adding WhatIf and Confirm Parameters to PowerShell API Calls

When I started to learn PowerShell, one of my favorite features was the inclusion of a -WhatIf parameter that all of the cmdlets offered to test out functionality without making changes. In essence, I could see what would happen without making it actually happen. This is a fairly wise course to pursue when doing anything in IT, especially against production data or services.

Pretty much.
Pretty much.

Recently, I was asked how to do this for one of the custom functions I’ve written to interact with a RESTful API. Specifically, one that changes data via the patch method. After giving myself a severe facepalm (for not having included this in the first place), I set about adding the feature.

Altering the CmdletBinding

The first step is to add a bit more code to the [CmdletBinding()] portion of the function. I wanted to add two things:

  • The SupportsShouldProcess attribute to enable -WhatIf and -Confirm
  • The ConfirmImpact attribute to set a threshold for the level of change

This can be done with a single line:

[CmdletBinding(SupportsShouldProcess = $true,ConfirmImpact='High')]

The function now supports the ShouldProcess logic check, which I’ll cover in a bit, and sets the impact level of the changes to High. Now, the function will allow for a -WhatIf parameter … but it doesn’t do anything, yet. To prove this, I’ll stick the new code into my function, called Protect-RubrikVM, and pass along a -WhatIf.

PS C:\Dropbox\Code\Rubrik> Protect-RubrikVM -VM 'SE-CWAHL-WIN' -SLA 'Gold' -WhatIf
PS C:\Dropbox\Code\Rubrik>

The function returned nothing back, and I don’t see a “What if” message. The reason? This is a custom function that uses Invoke-WebRequest and there’s nothing dictating which part of the code should be skipped during a -WhatIf test. Let’s fix that by adding a tiny bit of additional logic to the code.

Using ShouldProcess Logic

All that’s left to do is find any section of the code that alters data and wrap it with a logic statement. Specifically, this statement:

if ($PSCmdlet.ShouldProcess("target","operation"))
{code to skip when someone uses -WhatIf}

When a user passes the -WhatIf parameter to the function, it will test the logic statement above and display a “What if” message instead of executing the code. Specifically:

What if: Performing the operation "operation" on target "target".

The message can be altered to suit your desires. Use text or variables in the operation and target sections. Here’s what I used for my Protect-RubrikVM function:

if ($PSCmdlet.ShouldProcess($VM,"Assign $SLA SLA Domain"))
{invoke the web request here}

And here’s the results.

PS C:\Dropbox\Code\Rubrik> Protect-RubrikVM -VM 'SE-CWAHL-WIN' -SLA 'Gold' -WhatIf
What if: Performing the operation "Assign Gold SLA Domain" on target "SE-CWAHL-WIN".
PS C:\Dropbox\Code\Rubrik>