views:

305

answers:

2

I am writing using JavaScript. I have a PID of a process. How do I kill it? You can terminate by a name using WMI, How can you do it using PID?

UPDATE: The platform is Windows.

+8  A: 

It looks like you're coding for either Windows Script Host or a Windows Desktop Gadget. If it is, I would use WScript.Shell and its Exec method along with the command line taskkill (Win XP Pro, Win Vista & Win 7 only):

var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("taskkill /pid 1234");

If you really want to do it with WMI something like the following works fine for me (thanks @Helen for the improvements):

function killPID (pid) {
  GetObject("winmgmts:").Get("Win32_Process.Handle='" + pid + "'").Terminate();
}
Andy E
I need it n windo 2000 and windows server 2003
Roman Dorevich
Why not use `ExecQuery("SELECT * FROM Win32_Process WHERE Handle='" + pid + "'")` instead of `InstancesOf` + `if`?
Helen
@Helen, you could do that, you'd still have to enumerate them though. It is a better method, I'll swap it with my code.
Andy E
On second thought, it can be even simpler - just `Get("Win32_Process.Handle='" + pid + "'")`, and no enumeration at all. (That's because `Handle` is a key property that uniquely identifies `Win32_Process` objects.)
Helen
@Helen: I tried that, it didn't work (threw an error actually). The original code I pasted here was part of a script that listed all running processes (like `tasklist`, but for something else), I didn't want to change it too much in case I broke it; my WMI expertise isn't that great beyond writing, enumerating and deleting registry keys :-)
Andy E
Sorry, I might've been unclear. The function body (if written in one line) can be `GetObject("winmgmts:").Get("Win32_Process.Handle='" + pid + "'").Terminate()`, and I can confirm this code works on Windows XP (provided that the process with the specified ID is found; otherwise an exception is thrown that can be caught with `try`...`catch`). And it should work on Windows 2000+, in fact.
Helen
@Helen: just came back around to this answer to check something and your one-liner worked fine. I forgot about it before, but I've updated it now.
Andy E
+1  A: 

For Windows 2000 you will need to install the Windows Support Tools and then use the Kill command from the shell as Andy E described in his answer..

Reference: http://articles.techrepublic.com.com/5100-10878_11-5031568.html

Gaby