Simple Strategy for Cmdlet Error Reporting

by Oct 28, 2016

In PowerShell, you can create complex error handlers but sometimes you might just want to know what went wrong so you can log it. No overkill needed.

Here are two cmdlets that probably will encounter some errors, and after these cmdlets complete, you find their results in $data1 and $data2, plus a lot of red error messages in your console:

$data1 = Get-ChildItem -Path c:\windows -Filter *.ps1 -Recurse 
$data2 = Get-Process -FileVersionInfo

Now take a look at this approach:

$data1 = Get-ChildItem -Path c:\windows -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -ErrorVariable errorList
$data2 = Get-Process -FileVersionInfo -ErrorAction SilentlyContinue -ErrorVariable +errorList

It’s not much more work to silence errors (-ErrorAction SilentlyContinue), and at the same time write the red error messages into your own private error variable $errorList. Note that -ErrorVariable expects the variable name (without the “$” accessor). Note also that prepending this variable name with “+” will add the error information to the variable rather than replacing it.

Now, both cmdlets run without visible error messages. At the end, you can easily analyze the errors collected in $errorList, and for example write them to some log file using Out-File:

$issues = $errorList.CategoryInfo | Select-Object -Property Category, TargetName
$issues
$issues | Out-File -FilePath $home\Desktop\report.txt -Append

Twitter This Tip! ReTweet this Tip!