Tasklist, multiple instances of a process and PID's

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
xga
Posts: 6
Joined: 03 Jan 2012 20:13

Tasklist, multiple instances of a process and PID's

#1 Post by xga » 28 Jul 2012 18:56

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!

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

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

#2 Post by Ed Dyreen » 28 Jul 2012 21:46

'
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

Squashman
Expert
Posts: 4484
Joined: 23 Dec 2011 13:59

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

#3 Post by Squashman » 29 Jul 2012 08:07

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.

Post Reply