Analyzing PowerShell Errors

by Aug 6, 2013

PowerShell logs all errors in $error variable (unless the cmdlet uses -ErrorAction Ignore). $error contains the error records which in turn contain a property named HistoryID that links to the command that produced the error.

By looking up the history list, you can produce a list of all errors that occurred in a PowerShell session, listing error message, time when command was executed, and the time it took to execute:

$error |
  # exclude errors that are no longer in the history list:
  Where-Object { $_.InvocationInfo.HistoryID -gt 0 } |
  # combine history and error information:
  ForEach-Object {
    # get history item for current error:
    $command = Get-History $_.InvocationInfo.HistoryID
    # calculate command execution time: 
    $duration = ($command.EndExecutionTime - $command.StartExecutionTime).TotalSeconds
    # get original error message:
    $errormessage = $_.Exception.Message

    # add information to history item:
    $command | Add-Member -MemberType NoteProperty -Name Error -Value $errormessage
    $command | Add-Member -MemberType NoteProperty -Name Duration -Value $duration

    # select properties to output:
    $result = $command | Select-Object -Property ID, Duration, Error, CommandLine, StartExecutionTime
  } |
  # list commands with highest duration first:
  Sort-Object -Property Duration -Descending |

Note that $MaximumHistoryCount controls how many items your history list keeps. You may want to increase the default value to cover a larger time frame.

Twitter This Tip! ReTweet this Tip!