dehiker
dehiker

Reputation: 454

Compare number of a specific process to a number

I get the number of a specific process with the help of this thread:

How to count amount of processes with identical name currently running, using a batchfile

I hope to assign the result of this command to a variable, then compare the variable with a number. My code is listed as below:

@echo off
setlocal enabledelayedexpansion 
set procName=chrome.exe
set a=tasklist /FI "IMAGENAME eq %procName%" 2>NUL | find /I /C "%procName%"
if !a! equ 1 (
    echo !a!
    echo %procName% starts to run...
) else (
    echo !a!
    echo %procName% has not run!
)

Here I got '0' for 'set a=tasklist /FI "IMAGENAME eq %procName%" 2>NUL | find /I /C "%procName%"' command. It also gives me "Echo closed" hint for 'echo !a!'.

FYI, when running the following command in cmd

tasklist /FI "IMAGENAME eq chrome.exe" 2>NUL | find /c /i "chrome.exe"

set a=tasklist /FI "IMAGENAME eq chrome.exe" 2>NUL | find /c /i "chrome.exe"

the output is 16 and 0 respectively.

What's the reason? How could I assign the result of a command to a variable? How to compare the variable to a number?

Thank you so much!

Upvotes: 1

Views: 1434

Answers (3)

James K
James K

Reputation: 4055

Well, set a=tasklist /FI "IMAGENAME eq chrome.exe" 2>nul | find /c "chrome.exe" does not work for me either. Which is good because I don't know how that was supposed to work.

I believe that this will be faster, because it doesn't have the overhead of FIND.EXE and writing, reading and deleting proc_temp.

set a=0
for /f "skip=3" %%x in ('tasklist /FI "IMAGENAME eq chrome.exe"') do set /a a=a+1
echo Total chrome.exe tasks running: %a%

EDIT: I just discovered that set /a does not require expanded variables and so removed the setlocal and endlocal commands and altered the set /a syntax.

Upvotes: 1

dehiker
dehiker

Reputation: 454

I think I found a solution:

tasklist /fi "imagename eq %procName%" 2>nul | findstr /i %procName% | find /c /v "">proc_temp
set /p current_num= < proc_temp
echo !current_num!

Also I think the code can be simplified. Hope some of you can give brief version :)

Upvotes: 0

rene
rene

Reputation: 42483

after this line in environment a has the pid of the process sought

for /F "tokens=1,2,*" %%a in ('tasklist /fi "imagename eq %procName%"') do if !%%a!==!%procName%!  set a=%b

Upvotes: 0

Related Questions