Translating Error Records

by May 3, 2017

Whenever PowerShell records an error, it wraps it in an Error Record object. Here is a function that takes such an error record and extracts the useful information:

#requires -Version 3.0 function Get-ErrorDetail {  param ( [Parameter(Mandatory,ValueFromPipeline)] $e ) process { if ($e -is [Management.Automation.ErrorRecord]) { [PSCustomObject]@{ Reason = $e.CategoryInfo.Reason Exception = $e.Exception.Message Target = $e.CategoryInfo.TargetName Script = $e.InvocationInfo.ScriptName Line = $e.InvocationInfo.ScriptLineNumber Column = $e.InvocationInfo.OffsetInLine Datum = Get-Date User = $env:USERNAME } } } } 

So if you’d like to know what your latest errors were, try this:

 PS C:> $error | Get-ErrorDetail | Out-GridView PS C:> 

Or, you can now easily ask a cmdlet to cache its errors, and evaluate them later. This example recursively searches the Windows folder for PowerShell scripts. You get the results, plus you get detailed information about any error that occurred while searching:

$files = Get-ChildItem -Path c:Windows -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -ErrorVariable myErrors $myErrors| Get-ErrorDetail | Out-GridView 

Twitter This Tip! ReTweet this Tip!