Page 1 of 1

Tasklist, multiple instances of a process and PID's

Posted: 28 Jul 2012 18:56
by xga
Hi All,

I'm writing a batch file to monitor a particular process every couple of minutes and if the memory of this process is over a certain threshold, it is killed and then restarted.

I have this working now, but the problem I'm facing is when there are multiple instances of the same process. E.G. Each tab open in the Chrome web browser, uses it's own instance of Chrome.exe with a unique PID.

When I use the command

Code: Select all

tasklist /fi "imagename eq chrome.exe"
it lists all of the instances of chrome.exe and displays their PID's. However, when I use the code

Code: Select all

for /f "tokens=2,3" %%A in ('tasklist /nh /fi "imagename eq chrome.exe"') do set PID=%%A
in my batch, it only provides the PID of the last instance of the process and not the first. I can use the command

Code: Select all

tasklist | find /I /C "chrome.exe"
to tell me the total number of instances, so I thought that I could create a loop to get each PID, but I'm not sure if this will work.

Would anyone be able to comment if this is at all possible and if so, any example code?

Thanks in advance!

Re: Tasklist, multiple instances of a process and PID's

Posted: 28 Jul 2012 21:46
by Ed Dyreen
'
Hi xga,

Code: Select all

@echo off &setlocal enableDelayedExpansion

set /a c = 0 &for /f "tokens=2,3" %%A in (

       'tasklist /nh /fi "imagename eq chrome.exe"'

) do   set /a c += 1 &set "PID.!c!=%%A"

set "PID"
set "c"

pause

Re: Tasklist, multiple instances of a process and PID's

Posted: 29 Jul 2012 08:07
by Squashman
Just wondering why you can't kill the task within the for loop. If you use the memusage option of tasklist, it should work like a charm.