Beta 42

Research and Development

Menu

PowerShell - Catching Errors

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'