Tags

,


Read Part 1 first!

My script containing the event logging stuff I posted at the weekend is getting massive and I’m getting fed up of writing long event logging lines and setting up arrays in the hashtable. I was also putting each entry into a logical order that matches where they might occur during runtime and so kept having to renumber the IDs as I inserted extra verbose logging. Since the EventIDs are consecutively numbered I decided there must be a way of using an in-built index for that instead.

The first thing to do was to make the Hastable [Ordered] since otherwise there is no concept of an index to a key. The next problem was finding a way to locate the index of a key in an unsorted Hashtable. I found the solution in a .NET static method:

$index = [Array]::IndexOf($orderedHashtable.Keys, $keyString)

I then thought it would be better to make the event logging into a function where I could pass in parameters to make the actual logging lines brief. The following code gives an example. The assumption is you’ve made the specified log and source already with the New-EventLog cmdlet. It also handles passing in arguments for “-f” .NET string formatting. Fortunately, that is quite forgiving if you pass them in but don’t use them. I’ve not added error checking except for the existence of the key.

function Write-CantorisEventLog {
    [CmdletBinding(PositionalBinding=$False)]
    Param (
        [System.Diagnostics.EventLogEntryType]$entryType = "Information",
        [Parameter(Mandatory=$True)]
        [string]$key,
        [string[]]$minusF = ""
    )

    $log = "Cantoris-PowerShell"
    $src = "Test-EventLogging"

    $eventIDs = @{
        "BEGIN_SCRIPT" = "Beginning execution of script.";
        "TEST_FORMATTING" = "Test arg 0 '{0}' and arg 1 '{1}'.";
        "FINISH_SCRIPT" = "Completed execution of script."
    }

    $index = [Array]::IndexOf($eventIDs.Keys, $key)
    if ($index -eq -1) {
        $msg = ("ERROR: Event log message with ID '{0}' is not defined." -f $key)
    } else {
        $msg = $eventIDs[$key] -f $minusF
    }
    Write-EventLog -LogName $log -Source $src -EntryType $entryType -EventId $index -Message $msg
}

Write-CantorisEventLog -key "BEGIN_SCRIPT"
Write-CantorisEventLog -key "TEST_FORMATTING" -entryType "Warning" -minusF "ZERO","ONE"
Write-CantorisEventLog -key "FINISH_SCRIPT" -entryType "Error"
Advertisements