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.
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 ...