Compare number of a specific process to a number

那年仲夏 提交于 2019-12-24 07:26:33

问题


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!


回答1:


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.




回答2:


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



回答3:


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 :)



来源:https://stackoverflow.com/questions/12210438/compare-number-of-a-specific-process-to-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!