Recipe 6.14. Script: Process TerminatorHave 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 VBScriptThe 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. Using a Command-Line InterfaceJust as with the Process Doctor, you can perform similar functionality to the Process Terminator using a command line. But fortunately, the command line in this case isn't quite as complicated. Here is the command-line version of the Process Terminator using the taskkill.exe command: > for /L %v in (1,1,10) do taskkill /IM calc.exe /F /T & sleep 60 The first part is very similar to the Process Doctor command line. This is a for loop that iterates from 1 to 10 by 1's. for /L %v in (1,1,10) The taskkill command matches any process with an image name of calc.exe and forcefully terminates its process tree (/F and /T): do taskkill /IM calc.exe /F /T Lastly, we sleep for 60 seconds and start the next iteration of the loop: & sleep 60 You can also do the same thing using the Sysinternals pskill.exe command: > for /L %v in (1,1,10) do pskill calc.exe & sleep 60 |