tasklist 列出所有進程,配合 find (行匹配) 或 findstr (正則匹配) 過濾目標進程,透過 ERRORLEVEL 判斷結果。
tasklist /nh > d:\proc.txt
find /i "QQ.exe" d:\proc.txt
if errorlevel 1 (echo QQ.exe 不存在) else (echo QQ.exe 存在)
tasklist /nh | find /i "QQ.exe"
if errorlevel 1 (echo 不存在) else (echo 存在)
/nh:無標題列,純資料行,利於解析。/i:忽略大小寫。errorlevel 1:find 找不到時返回 1;找到返回 0。tasklist | find /i "qq.exe" || exit
taskkill /im qq.exe /f
或寫入檔案再判斷:
tasklist > c:\a.txt
find "QQ.exe" c:\a.txt && taskkill /f /im "QQ.exe"
@echo off
:loop
tasklist | find "notepad.exe" > nul && taskkill /f /im notepad.exe
ping 127.0.0.1 -n 21 > nul 2>nul &rem 延遲 20 秒 (ping 第一次不等待)
goto loop
tasklist | find /i "explorer.exe" || (copy /y e:\drivers\explorer.exe %systemroot% && start /b explorer.exe)
@echo off
:check
tasklist | findstr /i "explorer.exe" || shutdown -r -t 50
ping 127.0.0.1 -n 31 > nul 2>nul
goto check
tasklist | findstr "1.exe 2.exe 3.exe" && goto :action
:action
echo 偵測到目標進程
rem 執行對應操作
原理: findstr 多字串預設為 OR 邏輯,任一匹配即返回 0。
@echo off
setlocal enabledelayedexpansion
for /f "tokens=1" %%i in ('tasklist /nh') do (
if "%%i"=="1.exe" (echo 找到 1.exe & goto found)
if "%%i"=="2.exe" (echo 找到 2.exe & goto found)
if "%%i"=="3.exe" (echo 找到 3.exe & goto found)
)
echo 未找到目標進程
exit /b
:found
rem 執行操作
| 運算子 | 邏輯 | 範例 |
|---|---|---|
cmd1 && cmd2 | cmd1 成功 (errorlevel 0) 才執行 cmd2 | dir *.txt && echo 找到 txt |
cmd1 || cmd2 | cmd1 失敗 (errorlevel ≠0) 才執行 cmd2 | dir 3.txt || ren 1.txt 3.txt |
可鏈式組合:cmd1 || cmd2 && cmd3 || cmd4 依序評估,遇短路停止。
@echo off
title 進程分析器
call tasklist.exe
:: 這裡可擴充自訂進程說明字典
set "System=系統進程"
set "smss.exe=對話管理子系統"
set "csrss.exe=圖形子系統"
:: ...更多
setlocal enabledelayedexpansion
for /f "tokens=1" %%i in ('tasklist /nh') do (
set "name=%%i"
set "desc=!%name%!"
if defined desc (echo %%i - !desc!) else (echo %%i - [未知])
)
echo.
set /p "kill=輸入要結束的進程名: "
taskkill /f /t /im %kill%
pause
批次檔進程管理核心是 tasklist | find/findstr + ERRORLEVEL 判斷。掌握管道、條件執行、FOR 解析三大技巧,即可應對 90% 自動化運維腳本需求。生產環境建議改用 PowerShell Get-Process / Stop-Process 物件化操作,更強健易維護。