Awesum Stuff

How to Kill a Process using VBScript/QTP

People say “Necessity is the Mother of Invention”, I think “Google Search is the Mother of all Inventions”…purely because a Software Engineer is incomplete without it. So I was doing my usual round of fighting with QTP (read – Creating a Script) and I was stuck with the need of killing a process after each iteration of my datatable. So (Mother) Google came to the rescue (for one of her countless Children). Lets just move to the point :-

Please note : The Below code can be executed by placing it in a .VBS file and just running it or can be executed through QTP.


'Method 1 - Killing a Process on your Machine :-

SET WshShell = CreateObject("WScript.Shell")

SET oExec=WshShell.Exec("taskkill /F /IM processname.EXE")

SET oExec= Nothing

SET WshShell =Nothing

'Method 2 - Alternative to above code (you can kill the process on another Machine as well with this code) :-

strComputer = "."
strProcessToKill = "processname.exe"

SET objWMIService = GETOBJECT("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

SET colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '" & strProcessToKill & "'")

count = 0
FOR EACH objProcess in colProcess
objProcess.Terminate()
count = count + 1
NEXT

' Use this when executing with VBS
wscript.echo "Killed " & count & " instances of " & strProcessToKill & " on " & strComputer     

' Use this when executing with QTP
Print "Killed " & count &" instances of " & strProcessToKill & " on " & strComputer  


SET objWMIService = Nothing

SET colProcess = Nothing

Advertisements

6 replies »

    • This also works fine. There are always “n” number of ways to do things.
      The advantage of using my approach is that we can also create a .vbs file which proves to be pretty handy if we need to manually close multiple processes.

      Thanks for sharing this.

  1. This line:

    FOR EACH objProcess in colProcess

    gives the following error:

    General run error. Line (29): “FOR EACH objProcess in colProcess”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s