Advanced Event Log Parsing in WSH - Filtering results
(Page 2 of 4 )
In the last article I challenge you to see if you could create a script that returned only Warning type events. As promised, we're going to take a look at how to do that.
First off, we need to figure out how to determine if an event is a Warning type. We know we can tell that by checking the event’s Type property. With that in mind, there are two ways to filter our results depending on how we want to handle the information.
The first way is to adjust the WMI query that we are using so that it only returns the information we want. We can do by adding a WHERE clause.
Set colEvents = objWMIService.ExecQuery( _
"SELECT * FROM Win32_NTLogEvent" WHERE Type = 'Warning'")
With this code, the WMI service only returns those items that are in the Win32_NTLogEvent class which have a Type property value of “Warning.” In other words, the collection only contains warning events.
This can be further filtered to return warnings from a specific log. Here’s an example:
Set colEvents = objWMIService.ExecQuery( _
"SELECT * FROM Win32_NTLogEvent" WHERE Type = 'Warning' " _
& "AND LogFile = 'System')
With the above query, only warning events from the System event log are returned in the collection.
The second way to filter events is by using conditional statements in VBS. We’re going to return all events in the colEvents collection, and then filter them ourselves so we can handle specific event types differently.
Set colEvents = objWMIService.ExecQuery( _
"SELECT * FROM Win32_NTLogEvent")
For Each objEvent In colEvents
If objEvent.Type = "Warning" Then
Set objEvent = colEvents.NextEvent()
objRs.AddNew
objRs("Category") = objEvent.Category
objRs("ComputerName") = objEvent.ComputerName
objRs("EventCode") = objEvent.EventCode
strMessage = objEvent.Message
If Len(strMessage) > 100 Then
strMessage = Left(strMessage, 100)
End If
objRs("Message") = strMessage
objRs("EventType") = objEvent.EventType
objRs("RecordNumber") = objEvent.RecordNumber
objRs("SourceName") = objEvent.SourceName
objRs("TypeDesc") = objEvent.Type
strUser = objEvent.User
If IsNull(strUser) Then strUser = "N/A"
objRs("UserName") = strUser
objRs("TimeGenerated") = Date2String(objEvent.TimeGenerated)
objRs("TimeWritten") = Date2String(objEvent.TimeWritten)
objRs.Update
End If
Next
Here the conditional statements separate event types as part of our For Each…Next loop. As a result, the colEvents collection still returns all events, but we can react differently based on types. Here warning events are written to the database. We could add an Else block to write remaining events to a different database if we wanted.
Next: More filtering examples >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer