我有一个名为“ Ulti.exe”的进程。由于我的项目要求,我可以同时运行多个副本。如果“ Ulti.exe”的副本数量下降到3以下,我需要终止所有进程,然后重新启动它们。
如何将TaskList计数保存到变量中?当前,以下命令:
TaskList | FIND /C "Ulti.exe"
如果键入cmd.exe,则会准确返回“ Ulti.exe”进程的数量。如何将其合并到.bat文件中,以便可以将此数字用作变量?
答案 0 :(得分:1)
通过for /f
循环获取命令的输出:
for /f %%a in ('TaskList ^| FIND /I /C "Ulti.exe"') do set count=%%a
echo %count%
答案 1 :(得分:0)
在计数的同时,您还可以收集PID以在需要时轻松杀死它们
:: Q:\Test\2018\11\02\SO_53115422.cmd
@Echo off & SetLocal EnableExtensions EnableDelayedExpansion
Set "Prog=Ulti.exe"
::Set "Prog=firefox.exe"
Set "Count="
Set "PIDs="
for /f "tokens=2" %%A in (
'TaskList /FI "IMAGENAME eq %Prog%" ^| Findstr /i "%Prog%"'
) do (
Set /A Count+=1
Set PIDs=!PIDs! /PID %%A
)
If defined Count (
If !Count! lss 3 (
echo taskkill %PIDs%
echo restart %Prog%
) else (
echo %Prog% running %Count% times [%PIDs%]
)
) else (
Echo %Prog% not running
Echo start %Prog%
)
示例输出:
> SO_53115422
Ulti.exe running 5 times [ /PID 3664 /PID 10332 /PID 3544 /PID 8996 /PID 11192]
> SO_53115422
Ulti.exe not running
start Ulti.exe
> SO_53115422
taskkill /PID 8056 /PID 2704
restart Ulti.exe
仅在测试时回显taskkill命令