Whenever writing scripts that are intended to automate something I always want to leave something behind so I can see if the script has run correctly.
Sometimes this can be as easy as a report to a file, e-mail or something like it.
However, in an enterprise environment you propably have a monitoring tool that also monitors the eventlogs of the operating systems… you can use that!
Would’t it be nice to configure your monitoring tools to pick up the your scripts leave behind?
So, the script would need to create an event in the Windows Event Log… Howto do that?
trap [Exception] { $log = Get-EventLog -List | Where-Object { $_.Log -eq "Application" } $log.Source = "MyScriptName" $log.WriteEntry("TRAPPED: $error[0]", [system.Diagnostics.EventLogEntryType]::Error,1234) exit }
You can simply modify the log source to the name of your script (where the error originated from) and the error ID (1234 in my example) Image may be NSFW.
Clik here to view.
And to convert it into a reusable function:
function Write-EventLog { [CmdletBinding()] [OutputType([int])] Param ( [Parameter(Mandatory=$true)][string]$LogName, [parameter(Mandatory=$true)][int]$EventID, [Parameter(Mandatory=$true)][string]$SourceName, [Parameter(Mandatory=$true)][string]$ErrorMessage ) trap [Exception] { $log = Get-EventLog -List | Where-Object { $_.Log -eq $LogName } $log.Source = $SouceName $log.WriteEntry("TRAPPED: $ErrorMessage", [system.Diagnostics.EventLogEntryType]::Error,$EventID) exit } }
Some of you may correctly think that this is taking the long way around since there is the Write-EventLog cmdlet.
By using this, you can accomplish the same:
trap [Exception] { Write-EventLog -LogName Application -source MyScriptName -EventId 1234 -message "TRAPPED: $error[0]" exit }
And to convert that into a function:
function Write-EventLog { [CmdletBinding()] [OutputType([int])] Param ( [Parameter(Mandatory=$true)][string]$LogName, [parameter(Mandatory=$true)][int]$EventID, [Parameter(Mandatory=$true)][string]$SourceName, [Parameter(Mandatory=$true)][string]$ErrorMessage ) trap [Exception] { Write-EventLog -LogName $LogName -source $SourceName -EventId $EventID -message "TRAPPED: $ErrorMessage" exit } }
As you can see there are multiple ways to accomplish your goal Image may be NSFW.
Clik here to view.