1

在被调用循环中如何完全停止批处理文件?

exit /b只是退出 :label 循环,而不是整个批处理文件,而 bareexit退出批处理文件父 CMD shell,这是不需要的。

@echo off
call :check_ntauth

REM if check fails, the next lines should not execute
echo. ...About to "rmdir /q/s %temp%\*"
goto :eof

:check_ntauth
  if not `whoami` == "nt authority\system" goto :not_sys_account
  goto :eof

:not_sys_account
  echo. &echo. Error: must be run as "nt authority\system" user. &echo.
  exit /b
  echo. As desired, this line is never executed.

结果:

d:\temp>whoami
mydomain\matt

d:\temp>break-loop-test.bat

 Error: must be run as "nt authority\system" user.

 ...About to "rmdir /q/s d:\temp\systmp\*"     <--- shouldn't be seen!
4

2 回答 2

1

You can stop it with a syntax error.

:not_sys_account
    echo Error: ....
    call :HALT

:HALT
call :__halt 2>nul
:__halt
()

The HALT function stops the batch file, it uses itself a second function so it can supress the output of the syntax error by redirection to nul

于 2013-10-08T20:47:48.557 回答
1

您可以设置ERRORLEVELfrom:not_sys_account子例程并将其用作返回值。主程序可以检查并更改其行为:

@echo off
call :check_ntauth

REM if check fails, the next lines should not execute
if errorlevel 1 goto :eof
echo. ...About to "rmdir /q/s %temp%\*"
goto :eof

:check_ntauth
  if not `whoami` == "nt authority\system" goto :not_sys_account
  goto :eof

:not_sys_account
  echo. &echo. Error: must be run as "nt authority\system" user. &echo.
  exit /b 1
  echo. As desired, this line is never executed.

与原始代码的区别在于exit /b 1现在指定了 anERRORLEVEL并且如果设置了则检查if errorlevel 1 goto :eof终止脚本ERRORLEVEL

于 2013-10-08T20:50:52.577 回答