批次檔(.bat/.cmd)是 Windows/DOS 自動化腳本的基礎。掌握 echo、if、goto、for、choice 等指令,即可撰寫強大的自動化流程。
| 指令 | 功能 | 範例 |
|---|---|---|
echo | 顯示訊息/開關指令回顯 | echo Hello / echo off |
@ | 單行隱藏指令回顯 | @echo off |
call | 呼叫另一批次檔(返回繼續執行) | call sub.bat |
pause | 暫停並提示「按任意鍵繼續」 | pause |
rem / :: | 註解行 | rem 這是註解 |
# 1. 字串比較 if "%1"=="a" format a: # 2. 檔案存在判斷 if exist config.sys edit config.sys # 3. 錯誤碼判斷(由大到小判斷) if errorlevel 3 goto err3 if errorlevel 2 goto err2 if errorlevel 1 goto err1
goto end :end echo 程式結束
choice /c:yme "請選擇 [Y]es [M]aybe [N]o" if errorlevel 3 goto no if errorlevel 2 goto maybe if errorlevel 1 goto yes
for %%f in (*.bat *.txt) do type %%f
批次檔中變數用 %%f,命令列直接執行用 %f。
@echo off :menu cls echo 1. 磁碟重組 echo 2. 顯示記憶體 echo 3. 結束 choice /c:123 /n "請選擇:" if errorlevel 3 goto end if errorlevel 2 goto mem if errorlevel 1 goto defrag :defrag c:\dos\defrag goto menu :mem mem goto menu :end echo 再見!
cmd /k test.bat 保留視窗觀察錯誤訊息。echo on 開啟指令回顯追蹤流程。setlocal enabledelayedexpansion 處理延遲變數展開(進階)。