Whenever PowerShell raises an error, an error record is written to $error which is an array storing the last errors that occurred.

You can try and manually extract relevant error information from ErrorRecord objects, or you can use 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"
    } 
  }
} 

The function uses two parameter sets, and valid ErrorRecord objects are automatically bound to $Record. If an object of different type is encountered that cannot be handled by this function, it is bound to $Alien.

To view detailed error information, try this:

 
PS> $error | ConvertFrom-ErrorRecord | Out-GridView
 

Twitter This Tip! ReTweet this Tip!

Anonymous