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

孤人 提交于 2019-11-30 15:02:07

问题


I would like to use a batch file to compare the number of processes named "standard.exe", that are running on my Windows 7 machine, with the number of processes named "basic.exe". If the amount of processes called "standard.exe" equals the amount of processes called "basic.exe" nothing should happen, if the numbers are unequal, basic.exe should be restarted.

Any ideas? Already found the following code to check whether a process is running, but now I would like to count the number of processes carrying the same name.

tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Programm is running

Thanks in advance!


回答1:


Using your example simply replace the /N in find with /C to return the count of processes.

tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /C "myapp.exe"

Then you can just reduce it down to :

tasklist | find /I /C "myapp.exe"

Although as Andriy M points out it will match both myapp.exe and notmyapp.exe.

As for the second part of your question, simply do this:

set a=tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /C "myapp.exe" 
set b=tasklist /FI "IMAGENAME eq myapp2.exe" 2>NUL | find /I /C "myapp2.exe" 
if not a==b do ( 
    stuff 
) 



回答2:


If you don't want to write a file, replace the tasklist and set var1 commands with

for /f "tokens=1,*" %%a in ('tasklist ^| find /I /C "standard.exe"') do set var1=%%a

same for the second ones.

for /f "tokens=1,*" %%a in ('tasklist ^| find /I /C "basic.exe"') do set var2=%%a



回答3:


There is probably a neater way to do it, but the following code seems to do the trick:

:begin
tasklist | find /I /C "standard.exe">D:\tmpfile1.txt
tasklist | find /I /C "basic.exe">D:\tmpfile2.txt
set /p var1= <D:\tmpfile1.txt
set /p var2= <D:\tmpfile2.txt
if %var1% LSS %var2% goto restart
if %var1% EQU %var2% goto wait

:wait
echo waiting..
ping -n 300 127.0.0.1 > nul
goto begin

:restart
echo error has occured, all processes will be restarted
taskkill /f /im standard.exe
taskkill /f /im basic.exe
ping -n 30 127.0.0.1 > nul

goto begin

Cheers!



来源:https://stackoverflow.com/questions/6550200/how-to-count-amount-of-processes-with-identical-name-currently-running-using-a

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