批处理文件无法抑制“终止作业”

2024-03-19

我试图打开第二个批处理文件并检测它是否正常退出或由用户关闭(ctrl+c 或 x 或窗口终止等..) 所以我使用下面的例子关闭时批量运行脚本 https://stackoverflow.com/questions/22559901/batch-run-script-when-closed

@Echo off
set errorlevel=1

    start /w %comspec% /c "mode 70,10&title Folder Confirmation Box&color 1e&echo.&echo. Else the close window&pause>NUL&exit 12345"
    echo %errorlevel%
    pause

我试图让第一批等待(/W),因为我稍后会检查错误级别 但是在关闭第二个批处理文件后,我收到类似 ^cterminate 批处理作业 (Y/N)? 的错误?

我尝试了这个建议https://superuser.com/questions/35698/how-to-supress-terminate-batch-job-y-n-confirmation https://superuser.com/questions/35698/how-to-supress-terminate-batch-job-y-n-confirmation

与脚本

rem Bypass "Terminate Batch Job" prompt.
if "%~2"=="-FIXED_CTRL_C" (
   REM Remove the -FIXED_CTRL_C parameter
   SHIFT
) ELSE (
   REM Run the batch with <NUL and -FIXED_CTRL_C
   CALL <NUL %1 -FIXED_CTRL_C %*
   GOTO :EOF
)

效果很好 那么有没有一种方法可以从同一个批处理文件开始并避免终止? 或者我是否必须从同一批次创建一个新批次并调用它? (我不想让他们也看到该文件)


  1. 不要给 a 赋值易失环境变量 http://ss64.com/nt/syntax-variables.html like errorlevel using set命令。这样做会导致它在当前上下文中变得不稳定。
  2. 总是使用title http://ss64.com/nt/start.html in START "title" [/D path] [options] "command" [parameters].
  3. start "" /W cmd /c "anycommand&exit /B 12345" always回报12345退出代码。这是因为所有的 cmd 行都带有&连接的命令在解析时准备好(与括在括号中的命令块相同),然后完整地、不可分割地运行。忽略&exit /B 12345从中获取正确的退出代码anycommand,或者用类似的东西替换它start "" /W cmd /c "anycommand&&exit /B 12345||exit /B 54321"仅获得成功/失败指示。

下一个代码片段可能会有所帮助:

@ECHO OFF
SETLOCAL enableextensions

set "_command=2nd_batch_file.bat"
:: for debugging purposes
set "_command=TIMEOUT /T 10 /NOBREAK"

:: raise errorlevel 9009 as a valid file name can't contain a vertical line 
invalid^|command>nul 2>&1

echo before %errorlevel%
start "" /w %comspec% /C "mode 70,10&title Folder Confirmation Box&color 1e&echo(&echo( Else the close window&%_command%" 
echo after  %errorlevel%

Output shows sample %_command% exit codes: 0 or 1 if came to an end properly but -1073741510 if terminated forceably by Ctrl+C or Ctrl+Break or red ×

==>D:\bat\SO\31866091.bat<nul
before 9009
after  0

==>D:\bat\SO\31866091.bat<nul
before 9009
after  1

==>D:\bat\SO\31866091.bat<nul
before 9009
^CTerminate batch job (Y/N)?
after  -1073741510

==>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

批处理文件无法抑制“终止作业” 的相关文章

随机推荐