Boost Your PowerShell Confidence with WhatIf

We’ve all had moments of instant regret. Maybe it was missing that WHERE clause when executing a SQL statement or seeing something like “500 rows affected” when expecting only 1. These are sinking feelings we never want to experience again.

To avoid that pain, SQL Server has BEGIN/ROLLBACK/COMMIT that you can use to help check your work. Did you know PowerShell also has a helpful switch called WhatIf to preview changes before they’re applied?

Let’s learn how to use WhatIf and see out how it can be the ultimate safety net when running scripts in PowerShell.

What is WhatIf

The WhatIf switch is used to preview changes that would result from running a PowerShell script. For example, running a script with WhatIf can give details on what files would be affected by a script had WhatIf not been used. We’ll look at an example like this below. It’s not necessary to use WhatIf for all scripts but it’s worth considering if you’re making changes.

How WhatIf Can Save You

Let’s say we’re done working with the Callihan SQL Server backup files and it’s time to delete them. We know our backups to delete are stored in “C:\Users\Chad\Desktop\PS_Backup” so we write the following script in PowerShell and add Whatif to check our work:

Do you see any issues? That same folder path also has a file named CALLIHAN_DO_NOT_DELETE that, based on the name, should not be deleted. Adding Whatif saved us from accidently deleting a file besides our old backups.

To make our script more accurate, let’s update our script to only remove files where the extension equals .bak. We’ll run the updated script but leave the Whatif to make sure we’re only removing the files we expect:

WhatIf shows that only the four .bak files would be removed. That’s what we expect so we’ll remove the Whatif and run the script to remove our old backups:

We’ll confirm our backups were removed and only the txt file remains:

Potential disaster has been avoided.

Thanks for reading!

One thought on “Boost Your PowerShell Confidence with WhatIf”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s