Powershell Best Practice #8: Use WhatIf and Confirm parameters

By | May 22, 2015

Best Practice: It is recommended to use the WhatIf and Confirm switch parameters when working with commands modifying the system state (Stop-Process, Set-ADUser, …).

Explanation:

The WhatIf and Confirm parameters are useful when you use them with commands that modify something.

WhatIf : Only displays the objects that would be affected and what changes would be made to those objects (without the worry of modifying those objects)
Confirm: Stops processing before any changes are made  to an object.

powershell-whatif-and-confirm-parameters

To list the optional common parameters: [System.Management.Automation.Cmdlet]::OptionalCommonParameters

optional-common-parameters

  • The WhatIf common parameter is used for “Simulation”, “Read-Only”: no action is performed, no write, no impact. Useful for simulation.
  • The Confirm common parameter is used to ask to the user to confirm that the action can be performed. Useful for confirmation.

You can also change the preference variables for global effect (but not recommended because it pollutes the user’s session):

  • $WhatIfPreference : True / False (default)
  • $ConfirmPreference: None / Low / Medium / High (default)

It is better to enable the parameter only for a specific cmdlet (it is a switch parameter and has the $true value when called):

what-if-parameter-powershell

To get the list of commands supporting the optional common parameters “WhatIf” or “Confirm”:

get-command-parameter-whatif

The list of verbs which supporting the -WhatIf parameter:

sort unique whatif cmdlets


You can add the -WhatIf and -Confirm parameters to your advanced function that way:

It is important to say that you don’t need to add SupportsShouldProcess for commands that are not modifying the system.

Ex: Set-ADUser modifies the system whereas that Get-ADUser performs only Read operations.

whatif


previous-buttonnext-button

Leave a Reply

Your email address will not be published.