Catching Errors

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Powershell Plus


13 Free SQL Tools from Idera


Free Ebook: Mastering Powershell

In forums, people often get confused with error handling. For example, this code does not call the error handler. Instead, the red PowerShell error message pops up:

try { Remove-Item \\$name\c$\windows\temp\filename.exe }
catch {Write "Not able to access files on $name"}

When you want to catch errors produced by cmdlets, always make sure you add the parameter -ErrorAction Stop to it. Only then will the cmdlet emit an exception that your script can handle. So this works:

try { Remove-Item \\$name\c$\windows\temp\filename.exe -ErrorAction Stop }
catch {Write "Not able to access files on $name"}

If you want error handling for all cmdlets, you can also change the default mode like this:

$ErrorActionPreference = 'Stop'

Twitter This Tip! ReTweet this Tip!


Posted Jan 27 2012, 06:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.