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.
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.
Related links
- ScriptRunner ActionPacks will help you automate tasks
- Try out ScriptRunner here
- ScriptRunner: Book a demo with our product experts