Wednesday, September 15, 2010

VBScript to query NT Event Log in last X minutes

Occasionally I have a need to query NT Event Logs on several systems for an error within the last few minutes/hours/days. I adapted some online sources and created a handy VBScript using WMI that searches remote systems for an eventID in a specified period of time.



serverName=wscript.arguments(0)
EventID=wscript.arguments(1)
SearchMinutes=wscript.arguments(2)

QueryServer serverName, EventID, SearchMinutes

SUB QueryServer(strServer, eventID, minutes)
    on error resume next
    oldDate = DateAdd("n", -1 * minutes, now())
    myDate = DatePart("yyyy",oldDate) & Right("00" & DatePart("m",oldDate),2) & Right("00" & DatePart("d",oldDate),2) & "000000.0-420"

    ' ----------------------------------------------------------
    ' WMI Core Section 
    Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strServer & "\root\cimv2")
    strQuery = "select * from Win32_NTLogEvent where logfile='System' and TimeGenerated > '" & myDate & "' and (EventCode='"& eventID &"')"
    SET colLoggedEvents = objWMI.ExecQuery(strQuery)
    ' ----------------------------------------------------------
    ' Next section loops through ID properties

    For Each objItem in colLoggedEvents
        insString=  "TimeGenerated='" & objItem.TimeGenerated & "' ComputerName='" & objItem.ComputerName & "'  EventCode='" & objItem.EventCode & "' "
        strMessage = Replace(objItem.Message,vbCrLf & vbCrLf,vbCrLf)
        strMessage = Replace(strMessage,vbTab & vbTab,vbTab)
        strMessage = Replace(strMessage,"\n\n","\n")
        for each strIns in Split(strMessage, vbCrLf)
            if InStr(strIns, vbTab) then
                strIns = Replace(strIns,vbTab,"")
                strAtt = Replace(Split(strIns,":")(0)," ","_")
                strVal = Trim(Split(strIns,":")(1))
                strTmp = " " & strAtt & "='" & strVal & "' "
                if strTmp <> " ='' " THEN insString = insString & strTmp
                strAtt=""
                strVal=""
                strTmp=""
            end if
        NEXT

        wscript.echo insString
        insString=""
    Next
END SUB


2 comments:

Ramana Singh said...

Why are you concatenating the string with & "000000.0-420"

Is it significant?

Kaushik R said...

in order to get the date and time standard format UTC greenwich time