Skip to the main content.

Unlocking the Power of PowerShell: Tips for Success

Power up your PowerShell: Stream errors to your custom handler

Here comes the next strategy to handle errors, after learning about realtime and delayed error handling before. 

Stream errors directly to your custom error handler

There are two default error handling strategies covered earlier in this series:

  • Realtime error handling using Try/Catch: Invoked immediately when the error occurs, but aborts the cmdlet which cannot continue after the error was emitted.
  • Delayed error handling using error variable: Errors are collected and can be handled only after a cmdlet has completed. 

Here is the third approach that can combine the benefits of the both default approaches: It handles errors in real time immediately when they occur, and it does not require cmdlets to abort or use ‑ErrorAction Stop:


Get-ChildItem -Path C:\Windows -Depth 1 -Filter *.log 2>&1 | ForEach-Object { if ($_ -is [System.Management.Automation.ErrorRecord]) { $text = $_ | Convert-ErrorRecord | Out-String Write-Host $text } else { $_ } }

 

As you can see, the cmdlet (in this example Get‑ChildItem) does not use ‑ErrorAction at all. It runs completely unaffected from any error handling.

Instead, all emitted errors from stream #2 are redirected to the regular output stream #1 and can now travel down the pipeline. This way, they can stream in real time.

The ForEach‑Object cmdlet can then separate the exceptions from stream #2 from the regular output from stream #1, and handle the received exceptions in real time, while at the same time let the cmdlet do its work uninterruptedly.

 

Good2know

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.

PowerShell Poster 2023

Get your poster here!

 

 

Related links 



Related posts

4 min read

For more clarity: Convert PowerShell error records into actionable data

Tired of juggling PowerShell error handling? Discover how to simplify your workflow with a versatile function that...

3 min read

What's catch without try in PowerShell? It's a trap – Read how to use it!

Are you familiar with try...catch error handling? What is a catch block without a try block? It's a trap – and here is...

3 min read

Seamless PowerShell: Handle errors without missing a beat!

As $error is a global variable, consider using your own logging variable for error handling so you don't affect other...

About the author: