Thursday, August 20, 2009

Finding Event ID's

A while back, I had the need to look for a particular EventID across all our SQL servers. The script I came up to do the work is here.

This was one of my earliest efforts so its a bit primitive, but works just fine. The main working portion of the script is a straighforward query of the Win32_NTLogEvent wmi class.

The fun part was converting the wmi time into something more usable/readable. I did this in a function that breaks the wmi time into discrete chunks & then strings them all back together in my preferred format. Additionally it modify's the new date/time to account for daylight savings.
Function Convert-WMITime

    #Break Date & Time into discreet elements
    $ds = [string]$WMITime.substring(21,4)
    $yr = [string]$WMITime.Substring(0,4)
    $mo = [string]$WMITime.substring(4,2)
    $dy = [string]$WMITime.substring(6,2)
    $tm = [string]$WMITime.substring(8,6)
    $hr = [string]$tm.Substring(0,2)
    $min = [string]$tm.substring(2,2)
    $sec = [string]$tm.substring(4,2)
    #Create string in desired format
    $s = "$mo/$dy/$yr " + $hr + ":" + $min + ":" + $sec
    #cast result as DateTime type
    $result = [DateTime]$s
    #Account for DST
    if ($cp = $ds.Contains("-240"))
        $result = $result.AddHours(-1)
    return $result


  1. This is a great example of working with substrings. I would point out however that the Powershell devs had the same issue. As a result, whenever you use Get-WMIObject, the commandlet sticks a method on the objects it returns to do this for you. So in your script, you could do this:

    add-member -in $_ -membertype noteproperty Time $($_.ConvertToDateTime($_.TimeWritten))

  2. Thanks EBGreen, I appreciate the input. I'm all for KISS so knowing an easier/cleaner method is cool.