![如何抑制Windows批次作業終止確認?](https://rvso.com/image/1665763/%E5%A6%82%E4%BD%95%E6%8A%91%E5%88%B6Windows%E6%89%B9%E6%AC%A1%E4%BD%9C%E6%A5%AD%E7%B5%82%E6%AD%A2%E7%A2%BA%E8%AA%8D%EF%BC%9F.png)
當 Windows 批次作業啟動程序(可執行檔)時,使用者可以按 Ctrl-C 來停止該程式。
這會導致 Windows 批次作業顯示「終止批次作業 (Y/N)」提示並等待按鍵。
如何抑制此提示並需要按任意鍵?
答案1
擴展@KTaTk的建議,只要你破壞條件中的回傳程式碼,它就會抑制「終止批次作業(Y/N)」提示。
我的解決方法是:
setlocal enabledelayedexpansion
program.exe & set SAVEDRC=!ERRORLEVEL! & call;
echo Return Code was %SAVEDRC%
exit /b %SAVEDRC%
請注意,有必要使用!ERRORLEVEL!
(延遲擴展)來取得同一複合語句中的值,因為%ERRORLEVEL%
(解析時擴展)不會反映程式中更新的回傳程式碼。
然後call;
函數在執行下一行之前將錯誤等級重設為 0。
最後(可選),我們使用已儲存的返回程式碼退出。如果它是 -1073741510 ( STATUS_CONTROL_C_EXIT
) 且父進程也是 cmd shell,那麼父進程將顯示該提示。
或者,似乎 ctrl-c 提示僅在另一個進程的回傳程式碼導致該退出程式碼時才會出現。所以創建一個功能直接退出而不更改 ERRORLEVEL 也會抑制提示:
program.exe & call:ignoreCtrlC
echo Return Code was %ERRORLEVEL%
goto:eof
:ignoreCtrlC
exit /b
答案2
您可以使用條件執行在啟動可執行檔的命令中:
my_executable.exe && exit 0 || exit 1
這會抑制任何提示並使用代碼 0 或 1 退出批次作業,具體取決於可執行檔的退出代碼。
這對於 Ctrl-C 和 Ctrl-Break 都有效。
答案3
鑑於 CTRL-BREAK 或 CTRL-C 已經是按鍵,您可能正在尋找無需按 CTRL-C 或 CTRL-BREAK 即可停止批次腳本的答案。
這個答案是為了以防萬一這是你的目標。
在 Batch 中,您可以使用標籤和 IF 語句在腳本中跳轉。
例如:
@echo off
:: -- Lets print something to the screen.
echo This is a test before the loop starts
:: -- Lets set a counter variable to 0, just to be sure.
set counter=0
:: -- Set loop beginning point
:begin
:: -- Increase the counter by one but don't display the result to the screen
set /a counter=counter+1 >nul
:: -- now, write it to the screen our way.
echo Progress: %counter% of 10
:: -- pause the script for a second but without any displaying...
ping localhost -n 2 >nul
:: -- see if we reached 10, if so jump to the exit point of the script.
if %counter%==10 goto exit
:: -- if we reached this point, we have not jumped to the exit point.
:: -- so instead, lets jump back to the beginning point.
:: -- identation is used so the loop clearly stands out in the script
goto begin
:: -- set exit point for this script
:exit
:: -- lets print a message. We don't have to, but its nice, right?
echo End of the script has been reached.
假設我們寫了 c:\temp\counter.cmd,這會產生以下輸出:
c:\temp>counter
This is a test before the loop starts
Progress: 1 of 10
Progress: 2 of 10
Progress: 3 of 10
Progress: 4 of 10
Progress: 5 of 10
Progress: 6 of 10
Progress: 7 of 10
Progress: 8 of 10
Progress: 9 of 10
Progress: 10 of 10
End of the script has been reached.