Any error in PowerShell code surfaces as an error record object. Check out the function below which extracts all relevant error information from such error record:

function Get-ErrorInfo

    $info = [PSCustomObject]@{
      Exception = $errorRecord.Exception.Message
      Reason    = $errorRecord.CategoryInfo.Reason
      Target    = $errorRecord.CategoryInfo.TargetName
      Script    = $errorRecord.InvocationInfo.ScriptName
      Line      = $errorRecord.InvocationInfo.ScriptLineNumber
      Column    = $errorRecord.InvocationInfo.OffsetInLine
      Date      = Get-Date
      User      = $env:username

This function makes error handling code a lot shorter and easier to understand. If you must respond immediately to an error, use the try/catch concept, and make sure you instruct cmdlets via -ErrorAction Stop to immediately stop when an error occurs:

    Stop-Service -Name someservice -ErrorAction Stop
    $_ | Get-ErrorInfo

If you want the code to complete, and only later check for errors that may have occurred, use -ErrorAction SilentlyContinue in conjunction with -ErrorVariable. Again, the function Get-ErrorInfo helps a lot:

$result = Get-ChildItem -Path C:\Windows -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -ErrorVariable myErrors
$myErrors | Get-ErrorInfo

Twitter This Tip! ReTweet this Tip!