How to find windows process by process id on commandline

7.5k views Asked by At

I have two processes running (foo.cmd and bar.cmd on Windows7 prof), which both check frequently if the other process is still running. Since each process knows the PID of the other process in the variable %FPID%, I used to check if the other process is still running like this

FOR /F "tokens=1,*" %%a in ('tasklist /FI "PID eq %FPID%" /NH ^| find /C "%FPID%"') do set COUNTP=%%a

If %COUNTP% was now bigger than 0, the other process was still running.

But every now and then %COUNTP% was equals 0 even if the other process was actually still running (It still wrote into logfiles). A second later it could be found again.

  • Which circumstances could lead to not find a running process by its ID like I do with the statement above?
  • Is there a better/nicer/faster way to check if a process for a certain PID is still active and running (on windows)?
1

There are 1 answers

0
Knuckle-Dragger On

Off the top of my head, I am looking at the __InstanceDeletionEvent class for a WMI event watcher. If you choose that route, this snip will get you in the right direction, courtesy the WMI Code Creator.

Basically WMI will wait and detect when the $pid closes, and execute commands within 1 second of that happening.

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance.ProcessId = 1900")

Wscript.Echo "Waiting for events ..."
Do While(True)
    Set objReceivedEvent = objEvents.NextEvent

    'report an event
    Wscript.Echo "__InstanceDeletionEvent event has occurred."

Loop