6.14. Script: Process Terminator

Have you ever wanted to prevent a process from running? Perhaps the process keeps starting and you haven't been able to find what is starting it. Or maybe you know what is causing the process to start, but you can't prevent it from happening. I called the script the Process Doctor because it tries to revive processes that die. In this recipe, I'll describe the opposite. The Process Terminator kills a certain process every time it tries to run.

Using VBScript

The code in this script is very similar to that of the Process Doctor. The primary difference is that instead of looking at instanceDeletionEvent objects, we are looking for instanceCreationEvent objects, that is, new instances of the calc.exe process. Here is the script:

' ------ SCRIPT CONFIGURATION ------
strProcess = "calc.exe"
strComputer = "."
' ------ END CONFIGURATION ---------
   
set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set colProcesses = objWMI.ExecNotificationQuery(_ 
                     "select * from _ _instanceCreationEvent " _ 
                   & " within 1 where TargetInstance isa 'Win32_Process' " _
                   & " and TargetInstance.Name = '" & strProcess & "'")
do 
   set objProcess = colProcesses.NextEvent
   WScript.Echo "Terminating process " & strProcess & _
                " (" & objProcess.TargetInstance.ProcessID & ")"
   objProcess.TargetInstance.Terminate
loop

Also, instead of creating a new instance of the process when a creation event is found, I terminate the process. For more on terminating process, see Recipe 6.3. ...

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.