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

问题描述 投票:0回答:3

我得到了这个脚本表格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

提前致谢

batch-file cmd process tasklist
3个回答
1
投票

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

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

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


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

Conditional if-statements

根据您的评论要求:

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

0
投票

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

@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

© www.soinside.com 2019 - 2024. All rights reserved.