O'Reilly logo

Windows Server Cookbook by Robbie Allen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.13. Script: Process Doctor

Have you ever wanted to know when a particular process terminates on a system? Perhaps an application is failing mysteriously and you find out about it only after a user complains. Or maybe you have an application that fails periodically and you want to start it up immediately after it fails. This is pretty easy to accomplish using both VBScript and the command line.

Using VBScript

With WMI and event handlers, process monitoring is straightforward. The following code monitors the calc.exe process, and as soon as it recognizes that it is no longer running, restarts it:

' ------ SCRIPT CONFIGURATION ------
strProcess = "calc.exe"  ' Image name of the process you want to monitor
strComputer = "."
' ------ END CONFIGURATION ---------
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set colProcesses = objWMI.ExecNotificationQuery(_ 
                     "select * from _ _instanceDeletionevent " _ 
                   & " within 2 where TargetInstance isa 'Win32_Process' " _
                   & " and TargetInstance.Name = '" & strProcess & "'")
do 
   set objProcess = colProcesses.NextEvent
   WScript.Echo "Process " & strProcess & _
                " (" & objProcess.TargetInstance.ProcessID & ") terminated"
   intRC = objWMI.Get("Win32_Process").Create(strProcess, , , intProcessID)
   if intRC = 0 Then
      Wscript.Echo strProcess & " started. PID: " & intProcessID
   else
      Wscript.Echo strProcess & " did not start.  Error code: " & intRC
   end if
loop

The main method to note in this script is ExecNotificationQuery, which executes a WQL query ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required