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 thought on “PowerShell: Catching Errors

Leave a Reply

Your email address will not be published.