PowerShell Script Hygiene

The ability to write quick and dirty PowerShell scripts is half the fun of writing PowerShell. We have, after all, more powerful programming languages and tools to develop more interesting code.

However, sometimes all you have is PowerShell, or you simply have scripts that are quite useful and are maturing.

Sometimes, you're not sure where your script will go, but you'd like to start on a good foundation just in case.

Today, two things you can do to keep your scripts clean from day zero.

Set-StrictMode

The first recommendation is setting strict mode.

Set-StrictMode -Version Latest

You can also pick a specific set of rules. The latest rules as of this writing are 3.0, and cover the following.

$ErrorActionPreference

The $ErrorActionPreference variable allows you to control what happens when a command fails.

The default is "Continue", which just logs the message and continues. This isn't unlike a .bat file, where you just get an errorlevel but the script keeps going.

However, a best practice is to not just keep going, and instead check things. Good .bat files do this after every step.

PowerShell has an easier mechanism, simply add this to your script.

$ErrorActionPreference = 'Stop'

Technically, this will throw an ActionPreferenceStopException, which means you get the chance to catch it with Try/Catch, but that's a topic for another post.

Now, if don't want that on a specific statement, you can append -ErrorAction Continue or -ErrorAction SilentlyContinue to the specific statement.

Furthermore, if you want to look at the error, you can add -ErrorVariable myvar and then test myvar, but at that point you're better off using more structured Try/Catch blocks (again, coming to a future post near you).

If curious, the Try Catch Finally and error handling in PowerShell post by Alisdair Craik is pretty good.

Happy scripting!

Tags:  codingpowershell

Home