What To Do / Not to Do in PowerShell: Part 2

If you're looking at, or writing, a PowerShell script, then you shouldnever see this anywhere in the file:

$ErrorActionPreference = 'SilentlyContinue'

Man, that makes me mad. What it's doing is shutting off error messages for the entire script - even the beneficial, "this is broken" error messages that you NEED to see in order to ensure the script is operating correctly or can be fixed. Folks will throw that evil line into a script because the script contains a command or two where they're anticipating an error, and they don't want the error messing up their script's output. I get that - but this is the wrong way to do it. It's the same as the "On Error Resume Next" that a lot of VBScript folks would add to the top of every script, and I disliked that just as much.

What to do instead?

If you have a command that you think might cause an error, and you want to suppress the error for that one command, there's a better way. For example, let's say I have a script that needs to delete a log file. There's a possibility that the file won't exist, and trying to delete a non-existent file will generate an error. I don't care about the error - after all, if the file is gone, then mission accomplished, right? Here's the right way to suppress just that one error:

Del -Path $logfile -ErrorAction 'SilentlyContinue'

Of course, I have to remember that I'd also be suppressing "Access Denied" errors, along with any other error that might occur when running that command. Without seeing an error message, I wouldn't know what the problem was, or even that there was a problem. Suppressing errors can be risky that way, because your script may not function as expected, and without an error message you won't know why - and might spend a LOT of time troubleshooting something completely unrelated! But when you need to suppress an error for one command, the universal -ErrorAction parameter is the way to do it. Every PowerShell cmdlet and function will accept this parameter; it's part of the set listed on the help for every cmdlet.

Discuss this Blog Entry 1

on Jun 8, 2012
IThis was something I was guilty of in the past. Now, with the advent of proper try/catch with it's strange and seemingly random definition of terminating/non-terminating errors, it means having to write the exact opposite. i.e. $ErrorActionPreference = 'Stop' Otherwise, the catch might fly past an error thus defeating the point of using it. Great blog btw.

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×