7.15. Script: Service Monitor

Have you ever had a pesky service that would stop for apparently no reason? Well, if you can't afford to buy a service monitoring application, you can write one yourself using WMI and event notifications.

The following code monitors the state of all services and reports any changes:

' This code displays the changes in state for the services on a computer.
Option Explicit
Dim strComputer : strComputer = "."
' ------ END CONFIGURATION ---------
Dim objWMI : set objWMI = GetObject("winmgmts:\\" & strComputer _
                                    & "\root\cimv2")
Dim colServices : set colServices = objWMI.ExecNotificationQuery( _
                     "select * from _ _instanceModificationEvent " _ 
                   & "within 2 where TargetInstance ISA 'Win32_Service'")
   Dim objSvc : set objSvc = colServices.NextEvent
   If objSvc.TargetInstance.State <> objSvc.PreviousInstance.State Then
      Wscript.Echo objSvc.TargetInstance.Name & _
                   " is " & objSvc.TargetInstance.State & _
                   " -- it was previously " & _
   end If

The main method to note in this script is ExecNotificationQuery. This method executes a WQL query and receives events that result from it. Let's break the query down.

The select statement pulls all _ _instanceModificationEvent objects:

"select * from _ _instanceModificationEvent "

So what is a _ _instanceModificationEvent object? Anytime an instance of a WMI object changes, it registers the change as an instanceModificationEvent. This is incredibly powerful. ...

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.