Are you familiar with try...catch error handling? What is a catch block without a try block? It's a trap and here is the explanation why and when it's useful.

Start using traps This is why they are helpful

Most advanced users are familiar with trycatch error handling. Here is an example:

try

{

    Write-Host 'Previous Command'

    $result = Get-ChildItem -Path $env:windir -Depth 1 -Filter *.log -ErrorAction Stop

    Write-Host 'Next Command'

}

catch

{

   $_.CategoryInfo | Select-Object -Property Category, TargetName  

}

There are a few caveats about using try...catch:

  • try...catch requires the cmdlet to *abort* its task in order to catch the exception (via ?ErrorAction Stop, or if a terminating exception is emitted in the first place).
  • Any exception within the Try block skips the remaining commands in that block. Therefore, the second Write?Host statement won't be executed.

This behavior may be desired, and that's when try...catch is the best choice.

However, if you do not want to skip any commands, you can use a trap instead (see below). And if you do not want to abort a cmdlet, but instead want to evaluate errors after the cmdlet completes, see our next tip in this series.

A trap is essentially a Catch block without a Try block. You can easily modify the code example above:

Scriptrunner Image

Remove try keyword and {} braces, and replace catch with trap, add continue and you get:

Write-Host 'Previous Command'

$result = Get-ChildItem -Path $env:windir -Depth 1 -Filter *.log -ErrorAction Stop

Write-Host 'Next Command'



trap

{

   $_.CategoryInfo | Select-Object -Property Category, TargetName  

   continue
}

There are two differences:

  • Because a trap is a global error handler, it works anywhere in your script without a try block. Each exception is handled individually, and no command is skipped. That's why the second Write?Host command is now being executed.
  • Since a trap does not handle the error by default, an additional continue statement is required if you want the exception to be handled. Without it, the exception would continue to bubble to the next caller, and eventually display a red error message in the console (in addition to whatever you do in the trap).

Your ultimate PowerShell Cheat Sheet

Unleash the full potential of PowerShell with our handy poster. Whether you're a beginner or a seasoned pro, this cheat sheet is designed to be your go-to resource for the most important and commonly used cmdlets.The poster is available for download and in paper form.

Get your poster here!

Related links