System Management

Unlocking the Mystery of WMI Events in MOM

Brian Wren


At a Glance:

  • Understanding the workings of WMI
  • MOM classes for event notification
  • Writing scripts to manipulate WMI objects
  • Sample event queries

Microsoft Operations Manager (MOM) is a great tool for keeping an eye on your environment, but it can sometimes be tricky to monitor a particular activity. If the activity can be watched through the Windows event log or a counter in Performance Monitor, then it is relatively easy to create a corresponding rule in MOM. If the activity cannot be monitored through one of these means, however, then a custom script is often needed. Such a script will typically be written to sample a particular resource on a predefined schedule and generate an alert upon detecting that the defined activity occurred.

For example, an application may rely on a Windows® process that is not a Windows service. If this process ends unexpectedly, there likely wouldn’t be an event written to the Windows event log or any other application log. The only way to determine if this process is still running is to execute a script on a periodic basis to ensure that it is still healthy. Rather than writing a custom script to sample a resource periodically, you can take advantage of Windows Management Instrumentation (WMI) events. Virtually every interesting activity in Windows generates a WMI event, and MOM includes a provider for monitoring all of them.

To monitor WMI events in MOM, a WMI event provider is created to collect the appropriate events generated on the monitored computer. An event processing rule uses this provider to generate a MOM alert.

Understanding WMI

In order to monitor WMI events in MOM, a basic understanding of WMI is required. WMI is the Microsoft implementation of Web-Based Enterprise Management (WBEM) as defined by the Distributed Management Task Force (DMTF). It is the primary management technology for Windows operating systems, permitting management of a variety of computing resources using a common language and common interfaces. You can write scripts with the WMI Scripting Library in order to inspect and modify computer resources represented by WMI classes. Before you do, however, there are a number of WMI concepts that you should know.

Common Information Model (CIM) Repository The CIM repository is the WMI schema that stores the class definitions that model WMI-managed resources. The repository holds the information required to work with live resources in the computing environment. It does not contain actual data about these resources since this data is dynamically retrieved as required. It is this schema that allows the wide variety of different resources to be uniformly managed.

Namespaces CIM classes are organized into namespaces. Each namespace in the CIM repository contains a logical group of related classes representing a specific technology or area of management. Any time a connection is made to WMI, a namespace must be specified. Only the classes contained within this namespace may be accessed by the connection.

The most important namespace for Windows management is root\cimv2. It contains the classes with the Win32_ prefix representing various components of the Windows operating system and hosting computer. Examples include Win32_Process (running processes in Windows), Win32_LogicalDisk (Windows logical disk drives), and Win32_ComputerSystem (the computer hosting Windows). This namespace also includes the CIM_DataFile class which can be used to monitor files and folders. Two other important namespaces are root\default, which contains registry events, and root\MOM, which contains classes for accessing MOM from external processes.

Class Every resource that can be managed by WMI is defined by a class. A class is a template for each type of resource and defines the properties that will be collected for that resource. Examples of common WMI classes are shown in Figure 1.

Figure 1 Sample WMI Classes

Class Description
Win32_Process Processes running on a Windows computer
Win32_ComputerSystem A computer running a Windows operating system
CIM_DataFile A file stored on a disk
MSFT_Alert An alert in MOM

Property A property is unique piece of information about an instance. All instances of a class will have the same set of properties although the values of each instance’s properties may differ. Some Properties of the Win32_Service class are shown in Figure 2.

Figure 2 Sample Properties of Win32_Service Class

Property Description
Name Unique name of the service
DisplayName Displayed name of the service
PathName The command-line path that was executed to start the service
StartMode Startup type of the service (Auto, Manual, or Disabled)
State Current state of the service (Running, Stopping, or Stopped)

Instance An instance is a unique occurrence of a particular class. For example, each service installed on a computer running Windows is an instance of the Win32_Service class. The C: drive is an instance of the Win32_LogicalDrive class. Figure 3 shows sample properties of one instance of the Win32_service class.

Figure 3 Sample Properties of a Win32_Service Instance

Property Description
Name Winmgmt
DisplayName Windows Management Instrumentation
PathName C:\WINDOWS\system32\svchost.exe -k netsvcs
StartMode Auto
State Running

WMI Events Just as each resource is identified by a WMI class, each type of WMI event is represented by a class. When an event occurs, an instance of the corresponding WMI event class is created. The two types of WMI event classes that are used by MOM are intrinsic and extrinsic. (Note that there is also an event class type of Timer that is rarely used. This type is not relevant to MOM so I won’t discuss it here.)

Intrinsic events are used to monitor resources that have a WMI class. Each time an instance of any such class is created, modified, or deleted, an intrinsic event is generated within the class’s namespace. The most common intrinsic event classes used in MOM are __InstanceCreationEvent, __InstanceDelectionEvent, and __InstanceModificationEvent. (Notice the double underscore characters at the beginning of each name.) Extrinsic events are used to monitor resources that are not represented by a WMI class. There is no common set of extrinsic events, and individual ones must be implemented for a particular resource using them.

The most common extrinsic events that would be used in MOM are for monitoring the registry. The registry must use extrinsic events since there is no WMI class for individual registry settings (the intrinsic events associated with the Win32_registry class represent the registry as a whole). The registry-related extrinsic events are RegistryKeyChangeEvent, RegistryTreeChangeEvent, and RegistryValueChangeEvent, and are located in the root\default namespace.

Other applications may implement extrinsic events that may be monitored. It is their responsibility to provide the names and other information for these events. The Application Center 2000 Management Pack, for example, has a number of WMI Event Providers using these events.

WMI Tools

Tools for working with WMI include CIM Studio and Object Browser, which may be used to inspect the WMI repository and determine the appropriate class and related properties to monitor. The toolset also includes the WMI Event Viewer and WMI Event Registration Editor.

While all of these tools are useful, all the required functionality for the purposes of this article can be achieved with CIM Studio, which is designed to work with classes defined in the CIM Repository. The first step in using WMI events in MOM is determining the class corresponding to the resource of interest, and CIM Studio may be used for this purpose.

When CIM Studio is started, you are required to connect to a namespace. This will default to root\cimv2, which is typically the namespace you will be using anyway. The namespace can be changed later by typing a new one into the textbox in the top left-hand corner of the UI. By default, you will be connecting to the local machine, but you may specify another computer by clicking on the computer button. Fortunately, WMI lets you connect to a remote repository as easily as to a local one. CIM Studio looks daunting when first started, and it does provide a complete set of services for working with WMI, but for the purposes of this article you won’t have to worry about most of that complexity.

The simplest method of locating a class is to search the repository. This is done by clicking on the binoculars button next to the namespace textbox (the result is shown in Figure 4). This example returns a set of classes that include the word "process" in their name, including the class I’m interested in: Win32_Process. Selecting this class will cause it to be displayed in the tree in the left pane. The details of the class will appear in the right pane (see Figure 5). The most important information is the list of properties. The property names may be used for specifying criteria in WMI notification queries.

Figure 4 Class Search in CIM Studio

Figure 4** Class Search in CIM Studio **

In addition to the structure of the class, CIM Studio can display the instances of the class with their values for each property. Instances can be viewed by clicking the Instances button with the appropriate class selected. The Instances button is located in the top-right of the CIM Studio window. It is circled in Figure 5.

Figure 5 Win 32_Process Class in CIM Studio

Figure 5** Win 32_Process Class in CIM Studio **

The instances viewed in CIM Studio represent live data extracted from the operating system. In the example of Win32_Process, these are the details of the processes currently running on the computer. Figure 6 shows an example. The information in this view can be valuable in determining the criteria required for a WMI query since the value of each property is provided.

Figure 6 Instance View in CIM Studio

Figure 6** Instance View in CIM Studio **

WMI Notification Queries

A WMI notification query leverages WMI events that provide notification when a particular action occurs. Executing a query creates a WMI event subscription, which is similar to a Simple Network Management Protocol (SNMP) trap. When the requested event occurs, the subscribing process is notified and can take appropriate action.

The query parameter of a WMI event provider is a WMI notification query and is the most important and most complex parameter of the provider. Therefore I’ll cover the structure of these queries in further detail. A WMI notification query typically includes the parts listed in Figure 7.

Figure 7 Sections of WMI Notification Event Query

Keyword Example Code Description
SELECT SELECT Specifies what properties are returned. Typically the * wildcard is used to simply retrieve all properties.
FROM FROM__InstanceCreationEvent Specifies the event class to query. This will be the extrinsic or intrinsic event class.
WITHIN WITHIN 60 Polling interval. Specifies how many seconds should elapse between samples. For intrinsic events only.
WHERE WHERE TargetInstance ISA ‘Win32_Process’ AND TargetInstance.Name = ‘notepad.exe’ Filters the results. For intrinsic events, will usually include the ISA keyword to specify the class of the TargetInstance.

Note that the WITHIN clause specifies the polling interval for intrinsic event classes. Because the class being monitored does not have a corresponding event provider, the WMI polling mechanism is used to periodically check if an intrinsic event has occurred for the particular class. This polling interval is specified by the WITHIN keyword and measured in seconds.

If the polling rate is set too low (typically under 30 seconds), then excess overhead may be generated. If the polling rate is set too high, then events may be missed. For example, if the polling rate is set to 60 seconds when looking for the creation of a Windows process, a process may start and end within the 60 seconds. In this case, no event would be recognized. In addition, the detection of the event will be delayed up to the length of the polling interval. A general rule of thumb for MOM notifications is to set the polling interval to 60 seconds. This ensures that MOM detects any events in under a minute, limiting overhead on the agent computer.

Extrinsic event classes typically do not require the WITHIN keyword since the class being monitored has its own event provider. In this case, the polling mechanism is not used. For intrinsic event classes, the WHERE clause will typically have two parts. The first part specifies the class being monitored using the TargetInstance object with the ISA keyword. Here’s an example:

WHERE TargetInstance ISA ‘Win32_Process’

The ISA keyword (is a) is similar to an equals sign, but must be used instead because TargetInstance is an object, not a simple string. Note that the name of the class (Win32_Process in the example) must be contained within single quotes.

The second part of the WHERE clause contains one or more filters to narrow the results. These will use the AND or the OR keyword and attributes of the TargetInstance object and potentially the PreviousInstance object. TargetInstance is generated by all events and represents the WMI instance resulting from the event. PreviousInstance is only generated by instance modification events and represents the instance just prior to the event. Both the TargetInstance object and the PreviousInstance object will be of the same class as the class being queried and have all the same attributes. Here’s an example:

SELECT * FROM __InstanceDeletionEvent
WHERE TargetInstance ISA ‘CIM_DataFile’
AND (TargetInstance.Name = ‘c:\\AppFolder\\CriticalFile1.Log’
OR TargetInstance.Name = ‘c:\\AppFolder\\CriticalFile2.Log’)

Note the use of single quotes to specify strings and double backslashes in place of each backslash. These are required conventions of WMI.

Extrinsic event classes will not use the TargetInstance object or the ISA keyword since their class is already defined. They will use the WHERE clause to filter results, as in the following example:

SELECT * FROM RegistryValueChangeEvent 
AND KeyPath=‘Software\\Mission Critical Software’ 
AND ValueName = ‘TraceLevel’

With extrinsic events, the properties are used with their simple name. This is distinctly different than intrinsic events, which are in the form TargetInstance.Property. This is because properties used in intrinsic events are properties of the TargetInstance object.

Testing WMI Queries

The most difficult part of creating a WMI notification provider and rule is writing and testing the WMI notification query. In order to test the query using MOM, a provider and event rule would need to be created, deployed to an agent, and then an activity simulated to trigger the MOM event. If there is a problem, there will be little available information to assist in determining the cause.

The Windows Management Instrumentation Tester (WBEMTest), which is installed by default on all computers running Windows XP, Windows Server 2003, and Windows 2000, can be used to test a WMI query quickly and easily prior to placing it in MOM. Note that the WMI Event Viewer and WMI Event Registration Editor can also be used for this purpose. These tools are more refined than WBEMTest but are also more complex. In addition, the WMI Event Registration Editor creates permanent registration which can remain after the tool is closed. WBEMTest is more straightforward to use and does not leave registrations after it is closed.

Let’s now look at the process for testing a WMI notification query. There is no icon for starting WBEMTest. Simply select Start | Run and type wbemtest. When it loads, connect to a WMI namespace by clicking on the Connect button. The only field in the resulting dialog box (shown in Figure 8) that will typically be required is the unlabeled box that requires the name of the namespace to connect to. This will typically be root\cimv2 or root\default. Change it if required and click Connect.

Figure 8 Connect to a Namespace

Figure 8** Connect to a Namespace **

Once a valid namespace has been specified, the buttons in WBEMTest become enabled. Click the Notification Query button to test the WMI Query Language (WQL) intended for MOM providers (see Figure 9). Once you do, a dialog box will appear to allow you to type in the WQL for a notification query. After clicking the Apply button, if there is a problem with the WQL, you will receive an immediate error message similar to ones in Figure 10. The error message may or may not be descriptive enough to help you root out the problem, but it is a clear indication that the query is invalid and requires modification.

Figure 9 Valid Namespace Connection

Figure 9** Valid Namespace Connection **

If the query is valid, then the dialog box in Figure 11 will be displayed. This dialog box is waiting for the defined event to occur and will display the results when it does. The WQL used in the example will fire each time a new process is created in Windows. You can test this by simply starting Notepad (assuming you used the query in Figure 7). The entry in the dialog box indicates that the event was fired as expected. If you double-click on the event, detailed information about it will appear (see Figure 12). There you’ll see the properties of the event.

Figure 10a Notification Query Error

Figure 10a** Notification Query Error **

Figure 10b Notification Query Error

Figure 10b** Notification Query Error **

The most interesting information is contained in the TargetInstance property, which is an object representing the instance of the WMI class that you are monitoring (in the example, this is the process that was just created). You can view the details of the target object by selecting TargetObject in the property list, selecting Edit Property, and then clicking the View Embedded button (see Figure 13).

Figure 11 Query Result Dialog Box

Figure 11** Query Result Dialog Box **

Figure 12 Event Details in WBEM Test

Figure 12** Event Details in WBEM Test **

If you find a result in the Query Result window after simulating the event you want to monitor, then your WQL has detected the intended event and is therefore valid. You may also find the detailed properties of the related instance to be useful, though, in further refining the criteria of the WQL since this will show the available properties and their values (see Figure 13).

Figure 13 TargetInstance Object Properties

Figure 13** TargetInstance Object Properties **

Providers and Event Rules

A provider is a source of information collected by MOM. All MOM event rules require a provider. The event rule collects information from the provider and applies its own criteria to determine if this information should be collected, generate an alert, or execute any of a number of responses. As the name would imply, a WMI event provider monitors for WMI events.

A WMI event provider requires the following information:

Namespace, the namespace in which the WMI class being queried exists.

Query, the WMI notification query. This is identical to the WQL that was created in the previous section.

Property List, which specifies the properties of the event class that are returned. It is typically left blank so that all properties are returned.

Figure 14 shows a sample WMI event provider. The query in this provider is identical to the one in the previous testing example and, in fact, was entered with a copy/paste to ensure there were no typos. The property list was purposely left blank to simply return all properties of the WMI event.

Figure 14 Sample WMI Event Provider

Figure 14** Sample WMI Event Provider **

Event Processing

Once the WMI provider has been created, an event rule is required based on the provider. If the provider is already specific enough (firing when the specific process is started, for example), then the event rule needs no criteria. It only needs to be configured to generate an alert or execute a response.

For example, suppose you want an alert to be generated when a process called notepad.exe is started. The following notification query could be used in the provider with no criteria on the event rule:

SELECT * FROM __InstanceCreationEvent 
WHERE TargetInstance ISA ‘Win32_Process’ 
AND TargetInstance.Name = ‘notepad.exe’

In this case, the event will only fire if a process called notepad.exe is started. The event rule does not need to provide additional criteria.

An alternate strategy would be to remove the specific criterion in the provider and use the following query:

SELECT * FROM __InstanceCreationEvent 
WHERE TargetInstance ISA ‘Win32_Process’

In this case, the event rule would generate an alert each time any process was started, regardless of its name. If you want to receive an alert only when notepad.exe is started, then the event would need to provide additional criteria, as I’ll explain.

Intrinsic Events For intrinsic events, the parameters of the generated MOM event contain information from the WMI event itself as opposed to the properties of the target instance, which is the information you would typically want. Unfortunately, WMI events in MOM lump the useful information into a single parameter, the text of which can be searched for the info you need. The entire set of properties of TargetInstance are contained in a long string in a single parameter for all events. For a modification event, an additional parameter holds the properties for PreviousInstance, which represents the instance prior to modification. Figure 15 lists the MOM event parameters that contain these sets of properties. These are the parameters that may be specified in the event criteria.

For example, to filter the generic provider from the query you just saw, the following criteria could be used: "Parameter 12 contains substring ‘notepad.exe’".

This is a simple, typical example. More complex criteria may be specified using regular expressions. For example, to determine if either Notepad or Calculator has been started, the following criteria could be used: "Parameter 12 matches regular expression ‘notepad.exe|calc.exe’".

Extrinsic Events The properties for extrinsic events are placed into the event parameters in order of their occurrence. This order will vary for each resource, so you may need to collect some sample events to determine which parameter contains each property. For example, the RegistryValueChangeEvent provides the following properties: Hive (parameter 11), Key Path (parameter 12), and Value Name (parameter 15).

The use of criteria for extrinsic events will vary depending on the provider. In the case of the registry, event criteria typically are not useful since the RegistryValueChangeEvent requires the Hive, Key Path, and Value Name to be specified in the query anyway. Other extrinsic events may allow more general queries.

Specific Provider Versus Generic Provider There are two basic strategies in determining whether to use a specific provider (with no criteria on the event rule) or a generic provider (with criteria on the event rule). Both will provide the same result, but each has distinct advantages and disadvantages.

If you use a generic provider, multiple events can share a single provider. For example, the provider may specify the creation of any process. Events attached to that provider would specify in their criteria which process they were looking for. This results in fewer providers. The drawback, however, is in greater overhead. The provider will register in WMI to receive events for every process that is started. Each time an event is received, MOM must do a text search on the description to determine if an event criteria has been matched.

If you use a specific provider, then more providers must be created. The overhead, however, is minimal since you will only receive the specific events from WMI you are interested in. The typical strategy is to use specific providers because of the minimal overhead. It is rare that complex criteria are required to the point that a large number of providers end up being used. This is not a hard and fast rule, however, and in those cases where a more general provider makes sense you should use one.

Generating an Alert The default description for an alert generated from an event rule is $Description$. This replicates the description from the event that generated the alert. In the case of a WMI event, this is not recommended, since the description will include the text from each event parameter. While useful information, it is not entirely presentable, as is shown in Figure 16.

Figure 16 Default WMI Event Description

__GENUS=2 (0x2)
instance of Win32_Process
Caption = "notepad.exe";
CommandLine = "\"C:\\WINDOWS\\system32\\notepad.exe\" ";
CreationClassName = "Win32_Process";
CreationDate = "20050112170509.053027-480";
CSCreationClassName = "Win32_ComputerSystem";
CSName = "MOM01";
Description = "notepad.exe";
ExecutablePath = "C:\\WINDOWS\\system32\\notepad.exe";
Handle = "372";
HandleCount = 17;
KernelModeTime = "100144";
MaximumWorkingSetSize = 1413120;
MinimumWorkingSetSize = 204800;
Name = "notepad.exe";
OSCreationClassName = "Win32_OperatingSystem";
OSName = "Microsoft Windows Server 2003 Standard Edition|C:\\WINDOWS|\\Device\\Harddisk0\\Partition1";
OtherOperationCount = "31";
OtherTransferCount = "2147344384";
PageFaults = 456;
PageFileUsage = 585728;
ParentProcessId = 3832;
PeakPageFileUsage = 585728;
PeakVirtualSize = "30822400";
PeakWorkingSetSize = 1826816;
Priority = 8;
PrivatePageCount = "585728";
ProcessId = 372;
QuotaNonPagedPoolUsage = 1640;
QuotaPagedPoolUsage = 25856;
QuotaPeakNonPagedPoolUsage = 1640;
QuotaPeakPagedPoolUsage = 33256;
ReadOperationCount = "0";
ReadTransferCount = "0";
SessionId = 1;
ThreadCount = 1;
UserModeTime = "0";
VirtualSize = "23449600";
WindowsVersion = "5.2.3790";
WorkingSetSize = "1826816";
WriteOperationCount = "0";
WriteTransferCount = "0";

A specific description is typically used in order to provide plain English to the operator receiving the alert. For example, rather then use $Description$ for the event in Figure 16, a more appropriate description for the alert would be "An instance of notepad.exe was started."

Launching a Script In addition to generating an alert, a common response to a rule based on a WMI event provider is launching a script. (An introduction to writing scripts in MOM can be found at "Scripting for MOM".) If a script is launched in this manner, it may well need access to the properties of the WMI instance that initiated the event. These properties are available in the event parameters, as noted earlier, but they are lumped together in a single string. It may require a significant number of string searches for the script to access individual properties of the instance.

The VBScript function in Figure 17 may be used in a MOM script to parse the text returned from a WMI event query. This will return a Dictionary object with the properties of the instance that may be used almost as if it were an object of that class. (Documentation on the Dictionary object may be found at "Dictionary Object".) The function works by performing string searches against the known format of the event parameter. It plucks out the individual properties and places them into items of the Dictionary object. This function may be called by passing the appropriate event parameter, depending on the instance desired. Here’s an example using the process creation:

Set objEvent = ScriptContext.Event
Set objWMIObject = _

WScript.Echo "Name: " & _ 
WScript.Echo "Process ID: " & _    objWMIObject.Item("ProcessId")
WScript.Echo "Executable path: " & _

Figure 17 VBScript Function to Extract WMI Object Properties

    Function GetWMIObject(strEventWMIString)

    Set GetWMIObject = CreateObject("Scripting.Dictionary")
    intClassRef = InStr(strEventWMIString,"instance of ") + 12
        strClass = Mid(strEventWMIString,intClassRef, _ 
    GetWMIObject.Add "__CLASS",strClass
    intAttributeStart = InStr(intClassRef,strEventWMIString,"{" & _
        Chr(10) & Chr(9)) + Len("{" & Chr(10) & Chr(9))
    strAttributeString = Mid(strEventWMIString,intAttributeStart, _
        InStr(intAttributeStart,strEventWMIString, _ 
        Chr(10) &  "};" & Chr(10)) - _
        intAttributeStart - 1)
    arrAttributes = Split(strAttributeString, ";" & Chr(10) & Chr(9)) 

    For i = 0 To UBound(arrAttributes)
        intSplitRef = InStr(arrAttributes(i),"=")
        strAttributeName = Trim(Left(arrAttributes(i),intSplitRef-1))
        strAttributeValue = Trim(Right(arrAttributes(i), _ 
        If Left(strAttributeValue,1) = """" Then 
            strAttributeValue = Mid(strAttributeValue,2, _ 
        End If
        GetWMIObject.Add strAttributeName,strAttributeValue

End Function

MOM Classes

Similar to the WMI classes provided by Windows, MOM provides WMI classes for accessing its objects—including alerts, events, and computers. These are primarily intended for access to MOM from outside processes (a custom connector, for example), but they can be used to detect actions in MOM otherwise not possible by using a WMI event provider referencing an intrinsic event for one of these classes. (Full documentation on the MOM WMI classes is provided in the MOM SDK.)

MOM WMI classes are stored in the root\MOM namespace and are only available on management servers. Because of this, any rule based on a WMI provider using a MOM class must be deployed to a computer group such as Microsoft® Operations Manager 2005 Servers. If it is deployed to an agent, it will fail since the root\MOM namespace will not exist.

For most operations, notifications with the MOM WMI classes are not useful from within MOM, since MOM provides more effective methods to detect these actions. For example, while you could create a WMI provider looking for an __InstanceCreationEvent of an instance of MSFT_Event (the name of the class for MOM events), it is much easier to simply create an event rule which is designed to detect this action.

Events based on MOM WMI classes can be useful, though, in detecting actions that MOM does not normally detect. The most obvious example is a change to an alert (represented by the class MSFT_Alert). An alert rule in MOM detects the creation of an alert, but there is no obvious means of detecting a change to an alert property, such as a change to the owner or to the resolution state. This action can be detected with the following query:

SELECT * FROM __InstanceModificationEvent 
WITHIN 60 WHERE TargetInstance ISA ‘MSFT_Alert’ 

This query will detect any change to any alert. In order to determine which property changed, a comparison between the TargetInstance and PreviousInstance needs to be included. The following example detects a change in the Resolution State:

SELECT * FROM __InstanceModificationEvent 
WHERE TargetInstance ISA ‘MSFT_Alert’ 
and TargetInstance.ResolutionState <> 

Here’s a query to detect change to the owner MOM alert:

SELECT * FROM __InstanceModificationEvent 
WHERE TargetInstance ISA ‘MSFT_Alert’ 
and TargetInstance.Owner <> PreviousInstance.Owner


Now that you have seen how you can use WMI and MOM to capture system events that you were unable to monitor before, you will undoubtedly find many uses for the concept, including watching events whose status had never interested you before. If you would like to see some more real-world examples with the code to match, take a look at the sidebar "Monitoring Events: Real Examples." Don’t forget to check out other resources indicated throughout this article, and download the MOM SDK. Plus, for more on how WMI itself works, see "Windows Management Instrumentation", "WMI Scripting Primer", and the book Microsoft Windows Scripting with WMI: Self-Paced Learning Guide by Ed Wilson (Microsoft Press®, 2005).

Monitoring Events: Real Examples

The following are some examples of various WMI events that may be monitored. For each example, you’ll see the details for the provider and the event rule(s) to generate an alert.

Process Ending This example generates an alert when a particular process on a computer stops. The process name in this example is "coreapp.exe". This may be a critical process for a particular application that is not a Windows service. Here for the provider namespace of root\cimv2 the provider-specific query is the following and there are no event rule criteria:

SELECT * FROM __InstanceDeletionEvent 
WHERE TargetInstance ISA ‘win32_process’ 
AND TargetInstance.Name = ‘coreapp.exe’

Here is the query for a general provider:

SELECT * FROM __InstanceDeletionEvent 
WITHIN 30 WHERE TargetInstance ISA ‘win32_process’

And the event rule criterion is: Parameter 12 contains substring ‘coreapp.exe’.

Stopping a Service This example generates an alert when a service stops by monitoring for a modification in an instance of the service class. You must check if the name of the service is the one you are interested in, if its current state is not running, and if its previous state was running. If the check on previous state is not performed, then we could be firing the alert for a simple modification to the service’s configuration as opposed to a change in its running state. The service used in this example is the IIS Web service. Here is the provider query for a specific provider when there are no event rule criteria:

SELECT * From __InstanceModificationEvent 
WITHIN 30 WHERE TargetInstance ISA ‘Win32_Service’ 
AND TargetInstance.Name = ‘w3svc’ 
AND PreviousInstance.State = ‘running’ 
AND TargetInstance.State <> ‘running’

For a partially specific provider under these same circumstances, the provider query and the event rule criteria are as follows:

SELECT * From __InstanceModificationEvent 
WITHIN 30 WHERE TargetInstance ISA ‘Win32_Service’ 
AND TargetInstance.Name = ‘w3svc’

And Parameter 11 contains substring ‘Running’. Parameter 13 doesn’t contain substring ‘Running’.

Creating a File This example monitors for the creation of a specific file. This may be an error log generated by an application. The creation of the file indicates that an error has occurred in the application. The name of the file in this example is c:\appdir\errorlog.txt. Note that there is no example of a generic provider since this is not recommended for a class as large and volatile as CIM_DataFile.

Here the provider query is the following and there are no event rule criteria:

SELECT * FROM __InstanceCreationEvent 
WITHIN 30 WHERE TargetInstance ISA ‘CIM_DataFile’ 
AND TargetInstance.Name = ‘c:\\appdir\\errorlog.txt’

Note the use of double backslashes (\\) in place of the backslash (\) character in the path.

File Modification This example is similar to the previous one but instead of the file being created, it monitors for the file being modified. There are no event rule criteria and the provider query is:

SELECT * FROM __InstanceModificationEvent 
WITHIN 30 WHERE TargetInstance ISA ‘CIM_DataFile’
AND TargetInstance.Name = ‘c:\\appdir\\errorlog.txt’

The Creation of a File within a Directory This example is similar to the previous one, but instead of looking for a specific file, the query monitors for any file created within a certain directory:

SELECT * FROM __InstanceCreationEvent 
WITHIN 30 WHERE TargetInstance ISA ‘CIM_DataFile’ 
AND TargetInstance.Path = ‘\\appdir\\’ and 
TargetInstance.Drive = ‘C:’

Modification of a Registry Key This example monitors for a change to a particular registry key. The sample key for this example is HKLM\Software\Company\Application\AdminLevel. Note that there is no example of a general provider since the RegistryValueChangeEvent requires the Hive, KeyPath, and ValueName to be specified in the query:

SELECT * FROM RegistryValueChangeEvent 
AND KeyPath=‘Software\\Company\\Application’ 
AND ValueName = ‘AdminLevel’

Modification of Alert Resolution State The example monitors for the change in the resolution state of a MOM alert:

SELECT * FROM __InstanceModificationEvent 
WHERE TargetInstance.ResolutionState <> 

Modification of Alert Owner This example monitors for the change to the owner of a MOM alert. Additional criteria are specified to exclude alerts that have already been resolved:

SELECT * FROM __InstanceModificationEvent 
WHERE TargetInstance.Owner <> PreviousInstance.Owner 
AND PreviousInstance.ResolutionState <> 255

Brian Wren is a Principal Consultant with Microsoft Consulting Services in Southern California. In addition to architecting and deploying a variety of solutions for customers, he writes and speaks regularly on management technologies. He can be reached at

© 2008 Microsoft Corporation and CMP Media, LLC. All rights reserved; reproduction in part or in whole without permission is prohibited.