Handling Cmdlet Errors without Interruption

by Jun 18, 2014

When you want to use error handlers with errors that occur inside a cmdlet, then you can only catch such exceptions when you set the -ErrorAction of that cmdlet to "Stop". Else, the cmdlet handles the error internally.

That's bad because setting -ErrorAction to "Stop" will also stop the cmdlet at the first error.

So if you want to not interrupt a cmdlet but still get all errors caused by the cmdlet, then use -ErrorVariable instead. This line gets all PowerShell scripts recursively inside your Windows folder (which can take some time). Errors are suppressed but logged to a variable:

Get-ChildItem -Path c:\Windows -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -ErrorVariable myErrors

When the cmdlet is done, you can examine the variable $myErrors. It contains all the errors that occurred. This would give you a list of subfolders, for example, that Get-ChildItem was unable to look into:


It uses automatic unrolling (introduced in PowerShell 3.0). So in PowerShell 2.0, you'd have to write:

$myErrors | Select-Object -ExpandProperty TargetObject

Twitter This Tip! ReTweet this Tip!