Windows バッチ ジョブの終了確認を抑制するにはどうすればよいですか?

Windows バッチ ジョブの終了確認を抑制するにはどうすればよいですか?

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 シェルである場合、親プロセスはそのプロンプトを表示します。


あるいは、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.

関連情報