Q: How can I use VBScript to stop a process if it's running?

A: In the FAQ “Q: How Can I Check For a Process By Using VBScript,” we looked at finding a process. Here’s how to kill it by using the process Terminate function. This also checks that the process is no longer present:

set objWMIService = GetObject ("winmgmts:")
foundProc = False
procName = "winword.exe"

for each Process in objWMIService.InstancesOf ("Win32_Process")
    If StrComp(Process.Name,procName,vbTextCompare) = 0 then
        foundProc = True
        procID = Process.ProcessId
    End If
Next
If foundProc = True Then
    WScript.Echo "Found Process (" & procID & ")"
    WScript.Echo "Killing Process"
    Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" &  procID)
    For Each objProcess in colProcessList    
        objProcess.Terminate()
    Next
    WScript.Sleep(1000) 'wait for a second
    Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" &  procID)
    If colProcessList.count = 0 Then
        WScript.Echo "Process killed"
    End If
End If
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish