How to Suppress PowerShell Errors

If you've read my blog at all over the last couple weeks, it's pretty obvious that I've taken a liking to PowerShell; however, it's not been all sunshine and daisies. PowerShell definitely has a learning curve, causes a lot of trial-and-error, and is not without its frustrations.

One of those frustrations is how to suppress warnings and errors. For example, on my desktop is a folder named Temp, and in this folder I want to recursively delete all subfolders named Junk. To do so with PowerShell is quite simple and looks like this:

set-location C:\Users\Dave\Desktop\Temp
get-childitem -recurse -force |
  where {$_.name -eq "Junk"} |
    foreach ($_) {remove-item $_.fullname -recurse -force}

This works fine, but the output looks like this, even though the script did in fact recursively delete all subfolders named Junk:

ps-silentycontinue1

Because the script did do its job properly, I guess it's not a huge deal, but it's very misleading. And it gets much worse because it will output that error message for each matching item, in this case for each Junk subfolder (just imagine a recursive delete on all .svn folders).

I put up with this behavior for awhile until I just couldn't take it anymore, knowing there *had* to be a way of suppressing these types of errors. It took some digging in to the get-help feature of PowerShell, but I finally found what I was looking for. If you type "get-help about_CommonParameters" at a PowerShell prompt, you'll see that one of the common parameters is ErrorAction, which is an enum of the following values: Continue (the default), Stop, SilentlyContinue, and Inquire.

So there it was, the answer I was looking for: SilentlyContinue. Now I can change the script to include an ErrorAction parameter with a SilentlyContinue value, like so:

set-location C:\Users\Dave\Desktop\Temp
get-childitem -recurse -force -erroraction silentlycontinue |
  where {$_.name -eq "Junk"} |
    foreach ($_) {remove-item $_.fullname -recurse -force}

And when I run the script again, here's the output:

ps-silentycontinue2

You see those error messages? Me neither :-)

Of course, you don't always want to suppress PowerShell errors; you still have to be smart about where to do it. But for stuff like this, it makes perfect sense. And keep in mind ErrorAction is not limited to the get-childitem commandlet I've shown above; it's referred to as a "common parameter" for a reason :-)

Tags: ,