PowerShell: Catching Errors

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'

One Response to “PowerShell: Catching Errors”

  1. ash June 8, 2012 at 6:17 am #

    Thanks very helpfull

Leave a Reply

revia in alcoholism