Brian Wren Systems Management

Unlocking the Mystery of WMI Events in MOM

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 To monitor WMI events in MOM, a WMI rule in MOM. If the activity cannot be monitored through one of these means, however, event provider is created to collect the ap- then a custom script is often needed. Such a script will typically be written to sample a propriate events generated on the monitored particular resource on a predefined schedule and generate an alert upon detecting that computer. An event processing rule uses this the defined activity occurred. provider to generate a MOM alert. For example, an application may rely on a Windows process that is not a Windows ser- vice. If this process ends unexpectedly, there likely wouldn’t be an event written to the Understanding WMI Windows event log or any other applica- In order to monitor WMI events in • Understanding the workings of WMI tion log. The only way to determine if this MOM, a basic understanding of WMI is re- • MOM classes for event notification process is still running is to execute a script quired. WMI is the Microsoft implementa- • Writing scripts to manipulate on a periodic basis to ensure that it is still tion of Web-Based Enterprise Management WMI objects healthy. Rather than writing a custom script (WBEM) as defined by the Distributed • Sample event queries to sample a resource periodically, you can Management Task Force (DMTF). It is take advantage of Windows Management the primary management technology for Brian Wren is a Principal Consultant with Microsoft Consulting AT A GLANCEAT Services in Southern California. In addition to architecting and de- Instrumentation (WMI) events. Virtually Windows operating systems, permitting ploying a variety of solutions for customers, he writes and speaks every interesting activity in Windows gen- management of a variety of computing regularly on management technologies. He can be reached at erates a WMI event, and MOM includes a resources using a common language and [email protected]. provider for monitoring all of them. common interfaces. You can write scripts 42 To get your FREE copy of TechNet Magazine subscribe at: www.microsoft.com/uk/technetmagazine with the WMI Scripting Library in order to inspect and modify computer resources Figure 1 Sample WMI Classes represented by WMI classes. Before you do, Class Description however, there are a number of WMI con- cepts that you should know. Win32_Process Processes running on a Windows computer Common Information Model (CIM) Win32_ComputerSystem A computer running a Windows operating system Repository The CIM repository is the WMI CIM_DataFile A file stored on a disk schema that stores the class definitions that MSFT_Alert An alert in MOM model WMI-managed resources. The re- pository holds the information required to Instance An instance is a unique occurrence __InstanceDelectionEvent, and __Instance­ work with live resources in the computing of a particular class. For example, each service ModificationEvent. (Notice the double un- environment. It does not contain actual installed on a computer running Windows derscore characters at the beginning of each data about these resources since this data is is an instance of the Win32_Service class. name.) Extrinsic events are used to moni- dynamically retrieved as required. It is this The C: drive is an instance of the Win32_ tor resources that are not represented by schema that allows the wide variety of dif- LogicalDrive class. Figure 3 shows sample a WMI class. There is no common set of ferent resources to be uniformly managed. properties of one instance of the Win32_ extrinsic events, and individual ones must Namespaces CIM classes are organised service class. be implemented for a particular resource into namespaces. Each namespace in the WMI Events Just as each resource is identi- using them. CIM repository contains a logical group of fied by a WMI class, each type of WMI event The most common extrinsic events that related classes representing a specific tech- is represented by a class. When an event oc- would be used in MOM are for monitoring nology or area of management. Any time a curs, an instance of the corresponding WMI the registry. The registry must use extrin- connection is made to WMI, a namespace event class is created. The two types of WMI sic events since there is no WMI class for must be specified. Only the classes contained event classes that are used by MOM are in- individual registry settings (the intrinsic within this namespace may be accessed by trinsic and extrinsic. (Note that there is also events associated with the Win32_registry the connection. an event class type of Timer that is rarely class represent the registry as a whole). The The most important namespace for used. This type is not relevant to MOM so registry-related extrinsic events are Registry­ Windows management is root\cimv2. It I won’t discuss it here.) KeyChangeEvent, RegistryTreeChangeEvent, contains the classes with the Win32_ pre- Intrinsic events are used to monitor re- and RegistryValueChangeEvent, and are lo- fix representing various components of the sources that have a WMI class. Each time an cated in the root\default namespace. Windows operating system and hosting instance of any such class is created, modi- Other applications may implement ex- computer. Examples include Win32_Process fied or deleted, an intrinsic event is gen- trinsic events that may be monitored. It is (running processes in Windows), Win32_ erated within the class’s namespace. The their responsibility to provide the names LogicalDisk (Windows logical disk drives), most common intrinsic event classes used and other information for these events. The and Win32_ComputerSystem (the computer in MOM are __InstanceCreationEvent, Application Center 2000 Management Pack, hosting Windows). This namespace also in- cludes the CIM_DataFile class which can be used to monitor files and folders. Two oth- Figure 2 Sample Properties of Win32_Service Class er important namespaces are root\default, Property Description which contains registry events, and root\ Name Unique name of the service MOM, which contains classes for accessing DisplayName Displayed name of the service MOM from external processes. PathName The command-line path that was executed to start the service Class Every resource that can be managed StartMode Startup type of the service (Auto, Manual, or Disabled) by WMI is defined by a class. A class is a template for each type of resource and de- State Current state of the service (Running, Stopping or Stopped) fines the properties that will be collected for that resource. Examples of common WMI Figure 3 Sample Properties of a Win32_Service Instance classes are shown in Figure 1. Property A property is a unique piece of in- Property Description formation about an instance. All instances Name Winmgmt of a class will have the same set of proper- DisplayName Windows Management Instrumentation ties although the values of each instance’s PathName C:\WINDOWS\system32\svchost.exe -k netsvcs properties may differ. Some Properties StartMode Auto of the Win32_Service class are shown in State Running Figure 2. TechNet Magazine October 2006 43 Systems Management

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 pro- vide a complete set of services for working with WMI, but for the purposes of this ar- ticle you won’t have to worry about most of that complexity. The simplest method of locating a class Figure 4 Class Search in CIM Studio is to search the repository. This is done by clicking on the binoculars button next to for example, has a number of WMI Event While all of these tools are useful, all the the namespace textbox (the result is shown Providers using these events. required functionality for the purposes of in Figure 4). This example returns a set of this article can be achieved with CIM Studio, classes that include the word “process” in WMI Tools which is designed to work with classes de- their name, including the class I’m inter- Tools for working with WMI include CIM fined in the CIM Repository. The first step ested in: Win32_Process. Selecting this Studio and Object Browser, which may be in using WMI events in MOM is determin- class will cause it to be displayed in the tree used to inspect the WMI repository and ing the class corresponding to the resource in the left pane. The details of the class will determine the appropriate class and related of interest, and CIM Studio may be used appear in the right pane (see Figure 5). The properties to monitor. The toolset, found for this purpose. most important information is the list of at go.microsoft.com/fwlink/?LinkId=70207 also in- When CIM Studio is started, you are re- properties. The property names may be cludes the WMI Event Viewer and WMI quired to connect to a namespace. This will used for specifying criteria in WMI notifi- Event Registration Editor. default to root\cimv2, which is typically the cation queries. In addition to the structure of the class, CIM Studio can display the instances of the class with their values for each proper- ty. 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. The instances viewed in CIM Studio rep- resent 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 re- quired for a WMI query since the value of each property is provided.

WMI Notification Queries A WMI notification query leverages WMI events that provide notification when a par- ticular action occurs. Executing a query creates a WMI event subscription, which is similar to a Simple Network Management Figure 5 Win32_Process Class in CIM Studio Protocol (SNMP) trap. When the requested 44 To get your FREE copy of TechNet Magazine subscribe at: www.microsoft.com/uk/technetmagazine Systems Management

Figure 6 Instance View in CIM Studio event occurs, the subscribing process is noti- rule of thumb for MOM notifications is to The ISA keyword (is a) is similar to an fied and can take appropriate action. set the polling interval to 60 seconds. This equals sign, but must be used instead be- The query parameter of a WMI event pro- ensures that MOM detects any events in cause TargetInstance is an object, not a sim- vider is a WMI notification query and is the under a minute, limiting overhead on the ple string. Note that the name of the class most important and most complex param- agent computer. (Win32_Process in the example) must be eter of the provider. Therefore I’ll cover the Extrinsic event classes typically do not re- contained within single quotes. structure of these queries in further detail. A quire the WITHIN keyword since the class The second part of the WHERE clause WMI notification query typically includes being monitored has its own event provider. contains one or more filters to narrow the the parts listed in Figure 7. In this case, the polling mechanism is not results. These will use the AND or the OR Note that the WITHIN clause speci- used. For intrinsic event classes, the WHERE keyword and attributes of the TargetInstance fies the polling interval for intrinsic event clause will typically have two parts. The first object and potentially the PreviousInstance classes. Because the class being monitored part specifies the class being monitored us- object. TargetInstance is generated by all does not have a corresponding event pro- ing the TargetInstance object with the ISA events and represents the WMI instance vider, the WMI polling mechanism is used keyword. Here’s an example: resulting from the event. PreviousInstance to periodically check if an intrinsic event WHERE TargetInstance ISA ‘Win32_Process’ is only generated by instance modification has occurred for the particular class. This polling interval is specified by the WITHIN keyword and measured in seconds. Figure 7 Sections of WMI Notification Event Query If the polling rate is set too low (typi- cally under 30 seconds), then excess over- Keyword Example Code Description head may be generated. If the polling rate SELECT SELECT Specifies what properties are returned. Typically the is set too high, then events may be missed. * wildcard is used to simply retrieve all properties. FROM FROM Specifies the event class to query. This will be the For example, if the polling rate is set to 60 __InstanceCreationEvent seconds when looking for the creation of a extrinsic or intrinsic event class. Windows process, a process may start and WITHIN WITHIN 60 Polling interval. Specifies how many seconds should end within the 60 seconds. In this case, no elapse between samples. For intrinsic events only. WHERE WHERE TargetInstance event would be recognised. In addition, the Filters the results. For intrinsic events, will usually ISA ‘Win32_Process’ AND include the ISA keyword to specify the class of the detection of the event will be delayed up to TargetInstance.Name = ‘notepad.exe’ TargetInstance. the length of the polling interval. A general TechNet Magazine October 2006 45 Systems Management

Figure 8 Connect to a Namespace Figure 9 Valid Namespace Connection Figure 10 Notification Query Errors

events and represents the instance just prior an activity simulated to trigger the MOM the resulting dialog box (shown in Figure to the event. Both the TargetInstance object event. If there is a problem, there will be 8) that will typically be required is the un- and the PreviousInstance object will be of little available information to assist in de- labelled box that requires the name of the the same class as the class being queried termining the cause. namespace to connect to. This will typically and have all the same attributes. Here’s an The Windows Management Instrument­ be root\cimv2 or root\default. Change it if example: ation Tester (WBEMTest), which is in- required and click Connect. SELECT * FROM __InstanceDeletionEvent stalled by default on all computers running Once a valid namespace has been speci- WITHIN 60 fied, the buttons in WBEMTest become en- WHERE TargetInstance ISA ‘CIM_DataFile’ Windows XP, Windows Server 2003 and AND (TargetInstance.Name = ‘c:\\AppFolder\\ Windows 2000, can be used to test a WMI abled. Click the Notification Query button CriticalFile1.Log’ to test the WMI Query Language (WQL) OR TargetInstance.Name = ‘c:\\AppFolder\\ query quickly and easily prior to placing it CriticalFile2.Log’) in MOM. Note that the WMI Event Viewer intended for MOM providers (see Figure 9). Note the use of single quotes to specify and WMI Event Registration Editor can also Once you do, a dialog box will appear to al- strings and double backslashes in place of low you to type in the WQL for a notifica- each backslash. These are required conven- The most difficult tion query. After clicking the Apply button, tions of WMI. if there is a problem with the WQL, you will Extrinsic event classes will not use the part of creating a receive an immediate error message similar TargetInstance object or the ISA keyword WMI notification to ones in Figure 10. The error message may since their class is already defined. They will or may not be descriptive enough to help use the WHERE clause to filter results, as in provider and rule you root out the problem, but it is a clear the following example: is writing and indication that the query is invalid and re- SELECT * FROM RegistryValueChangeEvent quires modification. WHERE Hive=’HKEY_LOCAL_MACHINE’ testing the WMI If the query is valid, then the dialog box in AND KeyPath=’Software\\Mission Critical Software’ notification query. Figure 11 will be displayed. This dialog box is AND ValueName = ‘TraceLevel’ waiting for the defined event to occur and will With extrinsic events, the properties are used be used for this purpose. These tools are display the results when it does. The WQL with their simple name. This is distinctly more refined than WBEMTest but are also used in the example will fire each time a new different than intrinsic events, which are in more complex. In addition, the WMI Event process is created in Windows. You can test the form TargetInstance.Property. This is be- Registration Editor creates permanent reg- this by simply starting Notepad (assuming cause properties used in intrinsic events are istration which can remain after the tool is you used the query in Figure 7). The entry properties of the TargetInstance object. closed. WBEMTest is more straightforward in the dialog box indicates that the event to use and does not leave registrations af- was fired as expected. If you double-click Testing WMI Queries ter it is closed. on the event, detailed information about it The most difficult part of creating a WMI Let’s now look at the process for testing will appear (see Figure 12). There you’ll see notification provider and rule is writing a WMI notification query. There is no icon the properties of the event. and testing the WMI notification query. for starting WBEMTest. Simply select Start The most interesting information is con- In order to test the query using MOM, a | Run and type wbemtest. When it loads, tained in the TargetInstance property, which provider and event rule would need to be connect to a WMI namespace by clicking is an object representing the instance of the created, deployed to an agent, and then on the Connect button. The only field in WMI class that you are monitoring (in the 46 To get your FREE copy of TechNet Magazine subscribe at: www.microsoft.com/uk/technetmagazine Systems Management

Figure 11 Query Result Dialog Box Figure 12 Event Details in WBEMTest Figure 13 TargetInstance Object Properties example, this is the process that was just vider. The query in this provider is identical created). You can view the details of the tar- to the one in the previous testing example get object by selecting TargetObject in the and, in fact, was entered with a copy/paste property list, selecting Edit Property and to ensure there were no typos. The property then clicking the View Embedded button list was purposely left blank to simply return (see Figure 13). all properties of the WMI event. If you find a result in the Query Result window after simulating the event you want Event Processing to monitor, then your WQL has detected the Once the WMI provider has been cre- intended event and is therefore valid. You ated, an event rule is required based on the may also find the detailed properties of the provider. If the provider is already specific Figure 14 Sample WMI Event Provider related instance to be useful, though, in fur- enough (firing when the specific process ther refining the criteria of the WQL since is started, for example), then the event Intrinsic Events For intrinsic events, the this will show the available properties and rule needs no criteria. It only needs to be parameters of the generated MOM event their values (see Figure 13). configured to generate an alert or execute contain information from the WMI event a response. itself as opposed to the properties of the tar- Providers and Event Rules For example, suppose you want an alert get instance, which is the information you A provider is a source of information to be generated when a process called note- would typically want. Unfortunately, WMI collected by MOM. All MOM event rules pad.exe is started. The following notification events in MOM lump the useful informa- require a provider. The event rule collects query could be used in the provider with no tion into a single parameter, the text of which information from the provider and applies criteria on the event rule: can be searched for the info you need. The its own criteria to determine if this informa- SELECT * FROM __InstanceCreationEvent WITHIN 60 entire set of properties of TargetInstance is WHERE TargetInstance ISA ‘Win32_Process’ AND tion should be collected, generate an alert TargetInstance.Name = ‘notepad.exe’ contained in a long string in a single param- or execute any of a number of responses. As In this case, the event will only fire if a eter for all events. For a modification event, the name would imply, a WMI event pro- process called notepad.exe is started. The an additional parameter holds the proper- vider monitors for WMI events. event rule does not need to provide addi- ties for PreviousInstance, which represents A WMI event provider requires the fol- tional criteria. the instance prior to modification. Figure lowing information: An alternative strategy would be to re- 15 lists the MOM event parameters that Namespace, the namespace in which move the specific criterion in the provider contain these sets of properties. These are the WMI class being queried exists. and use the following query: the parameters that may be specified in the Query, the WMI notification query. This SELECT * FROM __InstanceCreationEvent WITHIN 60 event criteria. is identical to the WQL that was created WHERE TargetInstance ISA ‘Win32_Process’ For example, to filter the generic provider in the previous section. In this case, the event rule would generate from the query you just saw, the following Property List, which specifies the prop- an alert each time any process was started, criteria could be used: “Parameter 12 con- erties of the event class that are returned. regardless of its name. If you want to receive tains substring ‘notepad.exe’”. It is typically left blank so that all prop- an alert only when notepad.exe is started, This is a simple, typical example. More erties are returned. then the event would need to provide ad- complex criteria may be specified using Figure 14 shows a sample WMI event pro- ditional criteria, as I’ll explain. regular expressions. For example, to deter- TechNet Magazine October 2006 47 Systems Management

mine if either Notepad or Calculator has Figure 15 Event Parameters been started, the following criteria could Event TargetInstance PreviousInstance be used: “Parameter 12 matches regular ex- pression ‘notepad.exe|calc.exe’”. __InstanceCreationEvent Parameter 12 - Extrinsic Events The properties for __InstanceDeletionEvent Parameter 12 - extrinsic events are placed into the event __InstanceModificationEvent Parameter 13 Parameter 11 parameters in order of their occurrence. This order will vary for each resource, so you may need to collect some sam- Figure 16 Default WMI Event Description ple events to determine which parameter

Description: contains each property. For example, the __CLASS=__InstanceCreationEvent RegistryValueChangeEvent provides the __DERIVATION=__InstanceOperationEvent,__Event,__IndicationRelated,__SystemClass following properties: Hive (parameter 11), __DYNASTY=__SystemClass __GENUS=2 (0x2) Key Path (parameter 12), and Value Name __NAMESPACE=//./root/CIMV2 (parameter 15). __PATH= __PROPERTY_COUNT=3 (0x3) The use of criteria for extrinsic events __RELPATH= will vary depending on the provider. In __SERVER=MOM05 the case of the registry, event criteria typi- __SUPERCLASS=__InstanceOperationEvent SECURITY_DESCRIPTOR= cally are not useful since the RegistryValue­ TargetInstance={ ChangeEvent requires the Hive, Key Path, instance of Win32_Process and Value Name to be specified in the query { Caption = “notepad.exe”; anyway. Other extrinsic events may allow CommandLine = “\”C:\\WINDOWS\\system32\\notepad.exe\” “; more general queries. CreationClassName = “Win32_Process”; CreationDate = “20050112170509.053027-480”; Specific Provider Versus Generic CSCreationClassName = “Win32_ComputerSystem”; Provider There are two basic strategies in CSName = “MOM01”; determining whether to use a specific pro- Description = “notepad.exe”; ExecutablePath = “C:\\WINDOWS\\system32\\notepad.exe”; vider (with no criteria on the event rule) Handle = “372”; or a generic provider (with criteria on the HandleCount = 17; event rule). Both will provide the same re- KernelModeTime = “100144”; MaximumWorkingSetSize = 1413120; sult, but each has distinct advantages and MinimumWorkingSetSize = 204800; disadvantages. Name = “notepad.exe”; OSCreationClassName = “Win32_OperatingSystem”; If you use a generic provider, multiple OSName = “ Server 2003 Standard Edition|C:\\WINDOWS|\\Device\\Harddisk0\\Partition1”; events can share a single provider. For ex- OtherOperationCount = “31”; ample, the provider may specify the creation OtherTransferCount = “2147344384”; PageFaults = 456; of any process. Events attached to that pro- PageFileUsage = 585728; vider would specify in their criteria which ParentProcessId = 3832; process they were looking for. This results PeakPageFileUsage = 585728; PeakVirtualSize = “30822400”; in fewer providers. The drawback, howev- PeakWorkingSetSize = 1826816; er, is in greater overhead. The provider will Priority = 8; PrivatePageCount = “585728”; register in WMI to receive events for every ProcessId = 372; process that is started. Each time an event QuotaNonPagedPoolUsage = 1640; is received, MOM must do a text search on QuotaPagedPoolUsage = 25856; QuotaPeakNonPagedPoolUsage = 1640; the description to determine if an event cri- QuotaPeakPagedPoolUsage = 33256; teria has been matched. ReadOperationCount = “0”; If you use a specific provider, then more ReadTransferCount = “0”; SessionId = 1; providers must be created. The overhead, ThreadCount = 1; however, is minimal since you will only re- UserModeTime = “0”; ceive the specific events from WMI you are VirtualSize = “23449600”; WindowsVersion = “5.2.3790”; interested in. The typical strategy is to use WorkingSetSize = “1826816”; specific providers because of the minimal WriteOperationCount = “0”; WriteTransferCount = “0”; 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 TIME_CREATED=127500519325625901 a hard and fast rule, however, and in those 48 To get your FREE copy of TechNet Magazine subscribe at: www.microsoft.com/uk/technetmagazine Systems Management

cases where a more general provider makes sense you should use one. Figure 17 VBScript Function to Extract WMI Object Properties

Generating an Alert The default descrip- Function GetWMIObject(strEventWMIString) tion for an alert generated from an event rule is $Description$. This replicates the Set GetWMIObject = CreateObject(“Scripting.Dictionary”) intClassRef = InStr(strEventWMIString,”instance of “) + 12 description from the event that generated strClass = Mid(strEventWMIString,intClassRef, _ the alert. In the case of a WMI event, this is InStr(intClassRef,strEventWMIString,Chr(10))-intClassRef) GetWMIObject.Add “__CLASS”,strClass not recommended, since the description will include the text from each event parameter. intAttributeStart = InStr(intClassRef,strEventWMIString,”{“ & _ Chr(10) & Chr(9)) + Len(“{“ & Chr(10) & Chr(9)) While useful information, it is not entirely strAttributeString = Mid(strEventWMIString,intAttributeStart, _ presentable, as is shown in Figure 16. InStr(intAttributeStart,strEventWMIString, _ Chr(10) & “};” & Chr(10)) - _ A specific description is typically used in intAttributeStart - 1) order to provide plain English to the opera- tor receiving the alert. For example, rather arrAttributes = Split(strAttributeString, “;” & Chr(10) & Chr(9)) then use $Description$ for the event in Figure For i = 0 To UBound(arrAttributes) intSplitRef = InStr(arrAttributes(i),”=”) 16 , a more appropriate description for the strAttributeName = Trim(Left(arrAttributes(i),intSplitRef-1)) alert would be “An instance of notepad.exe strAttributeValue = Trim(Right(arrAttributes(i), _ was started”. Len(arrAttributes(i))-intSplitRef)) If Left(strAttributeValue,1) = “””” Then Launching a Script In addition to generat- strAttributeValue = Mid(strAttributeValue,2, _ ing an alert, a common response to a rule Len(strAttributeValue)-2) based on a WMI event provider is launching End If GetWMIObject.Add strAttributeName,strAttributeValue a script. (An introduction to writing scripts Next in MOM can be found at microsoft.com/technet/ scriptcenter/hubs/mom.mspx.) If a script is launched End Function in this manner, it may well need access to the properties of the WMI instance that initiated WScript.Echo “Executable path: “ & _ actions. For example, while you could the event. These properties are available in objWMIObject.Item(“ExecutablePath”) the event parameters, as noted earlier, but create a WMI provider looking for an they are lumped together in a single string. MOM Classes __InstanceCreationEvent of an instance It may require a significant number of string Similar to the WMI classes provided by of MSFT_Event (the name of the class for searches for the script to access individual Windows, MOM provides WMI classes MOM events), it is much easier to simply properties of the instance. for accessing its objects—including alerts, create an event rule which is designed to detect this action. The VBScript function in Figure 17 may events and computers. These are primarily be used in a MOM script to parse the text intended for access to MOM from outside Events based on MOM WMI classes can returned from a WMI event query. This processes (a custom connector, for exam- be useful, though, in detecting actions that will return a Dictionary object with the ple), but they can be used to detect actions MOM does not normally detect. The most properties of the instance that may be used in MOM otherwise not possible by using obvious example is a change to an alert almost as if it were an object of that class. a WMI event provider referencing an in- (represented by the class MSFT_Alert). An (Documentation on the Dictionary object trinsic event for one of these classes. (Full alert rule in MOM detects the creation of an alert, but there is no obvious means of may be found at microsoft.com/technet/scriptcen- documentation on the MOM WMI classes detecting a change to an alert property, such ter/guide/sas_scr_ildk.mspx.) The function works is provided in the MOM SDK.) by performing string searches against the MOM WMI classes are stored in the root\ as a change to the owner or to the resolu- known format of the event parameter. It MOM namespace and are only available tion state. This action can be detected with the following query: plucks out the individual properties and on management servers. Because of this, SELECT * FROM __InstanceModificationEvent WITHIN places them into items of the Dictionary ob- any rule based on a WMI provider using 60 WHERE TargetInstance ISA ‘MSFT_Alert’ ject. This function may be called by passing a MOM class must be deployed to a com- This query will detect any change to any the appropriate event parameter, depending puter group such as Microsoft Operations alert. In order to determine which prop- on the instance desired. Here’s an example Manager 2005 Servers. If it is deployed to erty changed, a comparison between the using the process creation: an agent, it will fail since the root\MOM TargetInstance and PreviousInstance needs Set objEvent = ScriptContext.Event namespace will not exist. to be included. The following example de- Set objWMIObject = _ GetWMIObject(objEvent.EventParameter(12)) For most operations, notifications with tects a change in the Resolution State: WScript.Echo “Name: “ & _ the MOM WMI classes are not useful SELECT * FROM __InstanceModificationEvent objWMIObject.Item(“Name”) WITHIN 60 WHERE TargetInstance ISA ‘MSFT_ WScript.Echo “Process ID: “ & _ from within MOM, since MOM provides Alert’ and TargetInstance.ResolutionState <> objWMIObject.Item(“ProcessId”) more effective methods to detect these PreviousInstance.ResolutionState 50 To get your FREE copy of TechNet Magazine subscribe at: www.microsoft.com/uk/technetmagazine Systems Management

Here’s a query to detect change to the owner that you were unable to monitor before, you article, and download the MOM SDK at MOM alert: will undoubtedly find many uses for the microsoft.com/mom/downloads/sdk. Plus, for more SELECT * FROM __InstanceModificationEvent WITHIN concept, including watching events whose on how WMI itself works, see microsoft.com/ 60 WHERE TargetInstance ISA ‘MSFT_Alert’ and TargetInstance.Owner <> status had never interested you before. If whdc/system/pnppwr/wmi, microsoft.com/resources/ PreviousInstance.Owner you would like to see some more real-world documentation/windows/2000/server/scriptguide/en-us/ examples with the code to match, take a sas_wmi_overview.mspx, and the book Microsoft Conclusion look at the sidebar “Monitoring Events: Windows Scripting with WMI: Self-Paced Now that you have seen how you can use Real Examples”. Don’t forget to check out Learning Guide by Ed Wilson (Microsoft WMI and MOM to capture system events other resources indicated throughout this Press®, 2005). l

Monitoring Events: Real Examples

The following are some examples of various WMI events example is c:\appdir\errorlog.txt. Note that there is no ex- that may be monitored. For each example, you’ll see the ample of a generic provider since this is not recommended details for the provider and the event rule(s) to generate for a class as large and volatile as CIM_DataFile. an alert. Here the provider query is the following and there are no event rule criteria: Process Ending This example generates an alert when a particular process on a computer stops. The process name SELECT * FROM __InstanceCreationEvent WITHIN 30 WHERE TargetInstance ISA ‘CIM_DataFile’ AND TargetInstance.Name = ‘c:\\appdir\\errorlog.txt’ in this example is “coreapp.exe”. This may be a critical pro- cess for a particular application that is not a Windows ser- Note the use of double backslashes (\\) in place of the back- vice. Here for the provider namespace of root\cimv2 the slash (\) character in the path. provider-specific query is the following and there are no File Modification This example is similar to the previous event rule criteria: one but instead of the file being created, it monitors for the SELECT * FROM __InstanceDeletionEvent WITHIN 30 WHERE TargetInstance ISA file being modified. There are no event rule criteria and the ‘win32_process’ AND TargetInstance.Name = ‘coreapp.exe’ provider query is: Here is the query for a general provider: SELECT * FROM __InstanceModificationEvent WITHIN 30 WHERE TargetInstance SELECT * FROM __InstanceDeletionEvent WITHIN 30 WHERE TargetInstance ISA ISA ‘CIM_DataFile’ AND TargetInstance.Name = ‘c:\\appdir\\errorlog.txt’ ‘win32_process’ And the event rule criterion is: Parameter 12 contains sub- The Creation of a File within a Directory This example string ‘coreapp.exe’. is similar to the previous one, but instead of looking for a Stopping a Service This example generates an alert when specific file, the query monitors for any file created within a service stops by monitoring for a modification in an in- a certain directory: stance of the service class. You must check if the name of SELECT * FROM __InstanceCreationEvent WITHIN 30 WHERE TargetInstance ISA ‘CIM_DataFile’ AND TargetInstance.Path = ‘\\appdir\\’ and the service is the one you are interested in, if its current TargetInstance.Drive = ‘C:’ state is not running, and if its previous state was running. If the check on previous state is not performed, then we Modification of a Registry Key This example monitors could be firing the alert for a simple modification to the for a change to a particular registry key. The sample key service’s configuration as opposed to a change in its run- for this example is HKLM\Software\Company\Application\ ning state. The service used in this example is the IIS Web AdminLevel. Note that there is no example of a general pro- service. Here is the provider query for a specific provider vider since the RegistryValueChangeEvent requires the Hive, when there are no event rule criteria: KeyPath, and ValueName to be specified in the query: SELECT * From __InstanceModificationEvent WITHIN 30 WHERE TargetInstance SELECT * FROM RegistryValueChangeEvent WHERE Hive=’HKEY_LOCAL_MACHINE’ AND ISA ‘Win32_Service’ AND TargetInstance.Name = ‘w3svc’ AND KeyPath=’Software\\Company\\Application’ AND ValueName = ‘AdminLevel’ PreviousInstance.State = ‘running’ AND TargetInstance.State <> ‘running’ For a partially specific provider under these same cir- Modification of Alert Resolution State The example cumstances, the provider query and the event rule criteria monitors for the change in the resolution state of a MOM are as follows: alert: SELECT * From __InstanceModificationEvent WITHIN 30 WHERE TargetInstance SELECT * FROM __InstanceModificationEvent WHERE ISA ‘Win32_Service’ AND TargetInstance.Name = ‘w3svc’ TargetInstance.ResolutionState <> PreviousInstance.ResolutionState And Parameter 11 contains substring ‘Running’. Parameter Modification of Alert Owner This example monitors 13 doesn’t contain substring ‘Running’. for the change to the owner of a MOM alert. Additional Creating a File This example monitors for the creation criteria are specified to exclude alerts that have already of a specific file. This may be an error log generated by an been resolved:

application. The creation of the file indicates that an error SELECT * FROM __InstanceModificationEvent WHERE TargetInstance.Owner <> has occurred in the application. The name of the file in this PreviousInstance.Owner AND PreviousInstance.ResolutionState <> 255

TechNet Magazine October 2006 51