Using ConvertFrom-ErrorRecord in try/catch

by Apr 26, 2018

In the previous tip we created a function called ConvertFrom-ErrorRecord that makes it easy to retrieve all relevant error information from PowerShell’s ErrorRecord objects.

You can use this function inside catch clauses as well. Just be sure you ran the function below:

function ConvertFrom-ErrorRecord
{
  [CmdletBinding(DefaultParameterSetName="ErrorRecord")]
  param
  (
    [Management.Automation.ErrorRecord]
    [Parameter(Mandatory,ValueFromPipeline,ParameterSetName="ErrorRecord", Position=0)]
    $Record,
    
    [Object]
    [Parameter(Mandatory,ValueFromPipeline,ParameterSetName="Unknown", Position=0)]
    $Alien
  )
  
  process
  {
    if ($PSCmdlet.ParameterSetName -eq 'ErrorRecord')
    {
      [PSCustomObject]@{
        Exception = $Record.Exception.Message
        Reason    = $Record.CategoryInfo.Reason
        Target    = $Record.CategoryInfo.TargetName
        Script    = $Record.InvocationInfo.ScriptName
        Line      = $Record.InvocationInfo.ScriptLineNumber
        Column    = $Record.InvocationInfo.OffsetInLine
      }
    }
    else
    {
      Write-Warning "$Alien"
    } 
  }
}

Here is an example how you can use ConvertFrom-ErrorRecord inside your catch clauses:

<pre><span style="color: #000000;">{
    </span><span style="color: #008000;"># this raises an error
</span><span style="color: #000000;">    </span><span style="color: #5F9EA0;">Get-Service</span><span style="color: #000000;"> </span><span style="color: #5F9EA0;">-Name</span><span style="color: #000000;"> </span><span style="color: #0000FF;">NonExisting</span><span style="color: #000000;"> </span><span style="color: #5F9EA0;">-ErrorAction</span><span style="color: #000000;"> </span><span style="color: #0000FF;">Stop</span><span style="color: #000000;">
}
</span><span style="color: #0000FF;">catch</span><span style="color: #000000;">
{
    </span><span style="color: #008000;"># pipe the errorrecord object through the new function
</span><span style="color: #000000;">    </span><span style="color: #008000;"># to retrieve all relevant error information
</span><span style="color: #000000;">    </span><span style="color: #008000;"># which you then could use to do error logging, or output
</span><span style="color: #000000;">    </span><span style="color: #008000;"># custom error messages
</span><span style="color: #000000;">    </span><span style="color: #000080;">$_</span><span style="color: #000000;"> </span><span style="color: #0000FF;">|</span><span style="color: #000000;"> </span><span style="color: #5F9EA0;">ConvertFrom-ErrorRecord</span><span style="color: #000000;">

}</span>
</pre>

Twitter This Tip! ReTweet this Tip!