Querying an Event Log for a Subset of Events

Microsoft® Windows® 2000 Scripting Guide

Querying an event log for a specific set of events can greatly increase the speed and efficiency of your query. The following examples demonstrate two ways to construct a script for determining the number of improper shutdowns recorded in the System event log with Event ID 6008 one way that is fast and efficient, another way that is not:

  • Retrieve all the events from the System event log, check each one to see whether the Event ID is 6008, and then report the total number of improper shutdown events found.

    On a Windows 2000-based test computer with approximately 700 events in the System event log, this process took more than 10 minutes.

  • Retrieve only events from the System event log that have Event ID 6008, and report the number of records retrieved by this query.

    On the same test computer, this query took just 9 seconds. If you know exactly what you are looking for, you should create a targeted query that returns only this information. This reduces processing time and, when you are working with remote computers, limits the amount of data that must be transferred across the network.

Scripting Steps

Listing 12.9 contains a script that queries an event log and tallies all instances of a specific Event ID. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace root\cimv2 on the computer, and set the impersonation level to "impersonate."

  3. Use the ExecQuery method to query the Win32_NTLogEvent class.

    To limit data retrieval to specific events, include a Where clause specifying the System event log and EventCode 6008. The resulting collection will include only records from the System event log that have EventCode 6008.

  4. Use the Count property to echo the number of records in the collection.

    Because a filter was applied as part of the GetObject call, the number of records in the collection equals the number of proper shutdowns recorded in the System event log.

Listing 12.9 Querying an Event Log for a Specific Event ID

  
1
2
3
4
5
6
7


strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLoggedEvents = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'System' AND " _
 & "EventCode = '6008'")
Wscript.Echo "Improper shutdowns: " & colLoggedEvents.Count

Show: