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

How to check if multiple processes is running via a batch script

我从 Whosebug 得到了这个脚本,它对我有用。因为我不能在那里发表评论,所以我在新 post.

中问我的问题

此脚本检查 exe 是否在任务列表中 运行:

@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

提前致谢

我对您的代码进行了一些不同的组织,因此它更容易理解并且具有更多功能。 注意: 这意味着如果您有 lots 个进程,它会更慢。如果您只想查看它是否存在,我建议您使用 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

这是我的解决方案,与您的示例脚本保持相似的结构。修改 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

如果要在找不到进程时启动程序,在ECHO %1 is not running后插入START %1

来自您的评论;如果您只想 运行 第三个可执行文件 如果其他两个可执行文件都不是 运行ning 那么这里是一个单行完整的批处理文件示例:

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

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