Monday, 4 August 2014

A Simple Script to Demonstrate Traps in PowerShell

In a quest to find an answer to “how do I log just thrown exceptions in PowerShell to a log file” the following two blog posts proved massively insightful:


And this simple script was born to simply throw an exception, demonstrate the wealth of information we can mine from that exception, and give an idea of what we can do with it. Knowing this is useful for unattended automation scripts that continue past errors, but where it might be required to revisit at a later date, check an error log, and see whether exceptions have been thrown.

There’s also probably a much simpler way to achieve the objective of the stated question...

## START OF SCRIPT ##

<#

A Simple Script To Demonstrate Traps in PowerShell
##################################################

All this script does is errors. It demonstrates what information we get from exceptions and how to use that information. One use case is logging only script exceptions to an error.log file. Save as say "demonstrateTraps.ps1" and run.

#>

# The simple "trap {trapOut}" must be placed inside the "territory" or "scope" where the error occurs (e.g. function, loop,...) if you want processing to continue!

Trap {TrapOut}

# The trap might need to be placed in many different "territory"s or "scope"s, so we create a simple function that the trap invokes every time it is triggered.

function TrapOut {

# TrapOut gets the date, gets the error message, and adds this to an error.log

$timeOfError  = (get-date).DateTime
$lineNumber   = $_.InvocationInfo.ScriptLineNumber
$offsetInLine = $_.InvocationInfo.OffsetInLine
$errorMessage = $_.Exception.Message

""
"TIME: LINE.CHARACTER :ERROR"
"==========================="
$timeOfError + ": " + $lineNumber + "." + $offsetInLine + " :" + $errorMessage
$timeOfError + ": " + $lineNumber + "." + $offsetInLine + " :" + $errorMessage >> error.log

# The following output simply displays what is available from an exception
""
"EXCEPTION gm (get-members)"
"=========================="
$_.Exception | gm
""
"PROPERTIES OF THE EXCEPTION'S Exception"
"======================================="
"CommandName                 :" + $_.Exception.CommandName
"Data                        :" + $_.Exception.Data
"ErrorRecord                 :" + $_.Exception.ErrorRecord
"HelpLink                    :" + $_.Exception.HelpLink
"InnerException              :" + $_.Exception.InnerException
"Message                     :" + $_.Exception.Message
"Source                      :" + $_.Exception.Source
"StackTrace                  :" + $_.Exception.StackTrace
"TargetSite                  :" + $_.Exception.TargetSite
"WasThrownFromThrowStatement :" + $_.Exception.WasThrownFromThrowStatement
""
"INVOCATION INFO gm (get-members)"
"================================"
$_.InvocationInfo | gm
""
"PROPERTIES OF THE EXCEPTION'S InvocationInfo"
"============================================"
"BoundParameters       :" + $_.InvocationInfo.BoundParameters
"CommandOrigin         :" + $_.InvocationInfo.CommandOrigin
"DisplayScriptPosition :" + $_.InvocationInfo.DisplayScriptPosition
"ExpectingInput        :" + $_.InvocationInfo.ExpectingInput
"HistoryId             :" + $_.InvocationInfo.HistoryId
"InvocationName        :" + $_.InvocationInfo.InvocationName
"Line                  :" + $_.InvocationInfo.Line
"MyCommand             :" + $_.InvocationInfo.MyCommand
"OffsetInLine          :" + $_.InvocationInfo.OffsetInLine
"PipelineLength        :" + $_.InvocationInfo.PipelineLength
"PipelinePosition      :" + $_.InvocationInfo.PipelinePosition
"PositionMessage       :" + $_.InvocationInfo.PositionMessage
"PSCommandPath         :" + $_.InvocationInfo.PSCommandPath
"PSScriptRoot          :" + $_.InvocationInfo.PSScriptRoot
"ScriptLineNumber      :" + $_.InvocationInfo.ScriptLineNumber
"ScriptName            :" + $_.InvocationInfo.ScriptName
"UnboundArguments      :" + $_.InvocationInfo.UnboundArguments
""

}

# This function does not exist but is enough to create an error for the trap to handle

thisFunctionDoesNotExistJustHereToCreateAnError

## END OF SCRIPT ##


No comments:

Post a Comment