萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Windows 批次檔/命令列判斷進程是否存在的多種技巧

核心工具:tasklist + find/findstr

tasklist 列出所有進程,配合 find (行匹配) 或 findstr (正則匹配) 過濾目標進程,透過 ERRORLEVEL 判斷結果。

基礎範例

1. 單進程檢測 (輸出到檔案再查)

tasklist /nh > d:\proc.txt
find /i "QQ.exe" d:\proc.txt
if errorlevel 1 (echo QQ.exe 不存在) else (echo QQ.exe 存在)

2. 管道直連 (無暫存檔,推薦)

tasklist /nh | find /i "QQ.exe"
if errorlevel 1 (echo 不存在) else (echo 存在)
  • /nh:無標題列,純資料行,利於解析。
  • /i:忽略大小寫。
  • errorlevel 1:find 找不到時返回 1;找到返回 0。

3. 直接殺掉進程 (一行流)

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"

進階場景

定時輪詢殺進程 (每 20 秒檢查 notepad)

@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

守護進程:偵測 explorer 掛掉則重啟

tasklist | find /i "explorer.exe" || (copy /y e:\drivers\explorer.exe %systemroot% && start /b explorer.exe)

進程不存在則重啟電腦 (每 30 秒檢查)

@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。

FOR 迴圈精確匹配進程名 (避免部分匹配誤判)

@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 && cmd2cmd1 成功 (errorlevel 0) 才執行 cmd2dir *.txt && echo 找到 txt
cmd1 || cmd2cmd1 失敗 (errorlevel ≠0) 才執行 cmd2dir 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 物件化操作,更強健易維護。

copyright © 萬盛學電腦網 all rights reserved