Supporting Risk Mitigation in PowerShell Functions

by Jan 3, 2018

When a PowerShell function performs system changes that may be risky, it is worth supporting the –WhatIf and –Confirm risk mitigation parameters. Here are the basic requirements:

function Test-WhatIf { [CmdletBinding(SupportsShouldProcess,ConfirmImpact='Low',HelpUri='http://www.myhelp.com')] param() if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Say 'Hello'")) { "I am executing..." } else { "I am simulating..." } } 

When you run this function, it properly honors the –WhatIf and –Confirm parameters:

 PS C:\> Test-WhatIf -WhatIf What if: Performing the operation "Say 'Hello'" on target "PC10". I am simulating... PS C:\> Test-WhatIf I am executing... PS C:\> 

It also defines a "ConfirmImpact" which can be "Low", "Medium", or "High", indicating how severe the changes are that the function performs.

When the confirm impact is equal or higher than the setting in $ConfirmPreference variable, PowerShell automatically displays a confirm message to the user:

 PS C:\> $ConfirmPreference = "Low" PS C:\> Test-WhatIf I am executing... Confirmation Do you really want to perform this action? ... I am simulating... 

Twitter This Tip! ReTweet this Tip!