如何通过批处理脚本检查是否正在运行多个进程

时间:2017-12-29 20:59:20

标签: batch-file cmd process tasklist

我有这个脚本表格stackoverflow,它为我工作。因为我不能在那里发表评论我在新帖子中提出我的问题。

此脚本检查exe是否在tasklist中运行:

@echo off
SETLOCAL EnableExtensions

set EXE=notepad.exe

FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto ProcessFound

goto ProcessNotFound

:ProcessFound

echo %EXE% is running
goto END
:ProcessNotFound
echo %EXE% is not running
goto END
:END
echo Finished!

问题是:

如何检查多个进程是否在任务列表上运行?

例如exe1和exe2

提前致谢

3 个答案:

答案 0 :(得分:1)

我已经对您的代码进行了有点不同的组织,因此它更容易理解并具有更多功能。 注意:这意味着如果您有批次进程,它会更慢。如果您只想知道它是否存在,我建议您使用findstr

我已添加REM(批量文件等效评论),解释了每个部分的用途。

@echo off

REM Create variable's for exe's and their counter
set exe_1=notepad.exe
set exe_2=explorer.exe
set exe_3=chrome.exe
set "count_1=0"
set "count_2=0"
set "count_3=0"

REM Store all tasklist findings in a temp file
>tasklist.temp (
tasklist /NH /FI "IMAGENAME eq %exe_1%"
tasklist /NH /FI "IMAGENAME eq %exe_2%"
tasklist /NH /FI "IMAGENAME eq %exe_3%"
)

REM Go through all finds and count for each task instance
for /f %%x in (tasklist.temp) do (
if "%%x" EQU "%exe_1%" set /a count_1+=1
if "%%x" EQU "%exe_2%" set /a count_2+=1
if "%%x" EQU "%exe_3%" set /a count_3+=1
)

REM Use variables to see instance count
Echo %exe_1%: %count_1%
Echo %exe_2%: %count_2%
Echo %exe_3%: %count_3%

REM Use GTR 0 to see if process exists
if %count_1% GTR 0 if %count_2% GTR 0 Echo Both notepad and explorer are open

REM Delete temp file once finished. (NB: Will still exist if your code crashes)
del tasklist.temp

条件if语句

根据您的评论要求:

if %count_1% GTR 0 if %count_2% GTR 0 (
    Echo Both notepad and explorer are open
    goto :finish
)
if %count_1% GTR 0 (
    Echo Only notepad is open
    goto :finish
)
if %count_2% GTR 0 (
    Echo Only explorer is open
    goto :finish
)

REM Not Finished means none are open
Echo Neither notepad nore explorer are open

:finish

答案 1 :(得分:1)

根据你的评论;如果你想要做的就是运行第三个可执行文件,如果其他两个可执行文件都没有运行,那么这里有一行完整的批处理文件示例:

@TaskList/NH /FI "Status Eq Running"|FindStr/IC:"first.exe" /C:"second.exe">Nul||Start "" "X:\PathTo\third.exe"

注意:
除名称firstsecondX:\PathTo\third外,不要更改任何内容; 所有双引号, " ,都是必要的!

答案 2 :(得分:0)

这是我的解决方案,保持与示例脚本类似的结构。修改EXE变量以引用您有兴趣检查的IMAGENAME

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET EXE=(notepad.exe wordpad.exe winword.exe thunderbird.exe outlook.exe greenshot.exe)
FOR %%i IN %EXE% DO (
    TASKLIST /NH /FI "IMAGENAME EQ %%i" 2>NUL | FIND /I /N "%%i">NUL
    IF !ERRORLEVEL! EQU 0 ( CALL :ProcessFound %%i ) ELSE ( CALL :ProcessNotFound %%i )
)

ECHO Finished^^!
EXIT /B 0

:ProcessFound
ECHO %1 is running
EXIT /B 0

:ProcessNotFound
ECHO %1 is not running
EXIT /B 1

如果您想在找不到流程时启动该计划,请在START %1之后插入ECHO %1 is not running