PowerTip: Use a destructive PowerShell cmdlet safely

Summary: Use the –whatif parameter with PowerShell cmdlets to test code live.

Hey, Scripting Guy! Question I heard that PowerShell has a built-in safety switch to many of its cmdlets. Could you show me an example of it in use?

Hey, Scripting Guy! Answer No problem. You’re referring to the –whatif parameter, which is meant to show you what would happen if you used a PowerShell cmdlet without actually executing the cmdlet. An example of this in action is in the following Remove-Item cmdlet.

This will attempt to remove the document, HSG-Article-Sean-Should-Not-Lose.docx, without actually removing it.

Remove-Item .\HSG-Article-Sean-Should-Not-Lose.docx -WhatIf

The Doctor

Comments (2)

  1. Elvith says:

    When you want to try a whole script that way rather than only a single command, you might want to use

    $WhatIfPreference = $true

    That way, all commands should behave like you added the -whatif switch until you reset it to false.

  2. @Elvith

    Excellent point! You could ALSO (Another neat trick) is set a variable at the beginning (or a parameter works well too) if you only have certain “Destructive cmdlets” you want the whatif flagged on. Example

    Remove-item c:\foo -whatif:$DoAWhatIf

    You can flip the value to true or false so you can Target the results 🙂

    Honorary Scripting Guy

Skip to main content