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

3 min read

Typed PowerShell Arrays and Generic Lists

Understanding the different array types in PowerShell is essential for efficient data management and automation in your...

3 min read

Optimizing PowerShell Performance: Using More Efficient and Flexible Arrays

Optimizing PowerShell arrays is key to improving script performance and ensuring efficient data handling in your...

3 min read

PowerShell Array Caveats: Common Issues and Solutions

Here is part two of our tips on PowerShell arrays.

Let’s explore some common caveats with arrays, starting with the...

About the author: