Windows 在“中”时完全停止批处理文件;调用:loop";

Windows 在“中”时完全停止批处理文件;调用:loop";,windows,batch-file,Windows,Batch File,在被调用的循环中,如何完全停止批处理文件 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

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

exit/b
仅退出:label循环,而不是整个批处理文件,而bare
exit
退出批处理文件和父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!
d:\temp>whoami
mydomain\matt
d:\temp>break-loop-test.bat
错误:必须以“nt authority\system”用户身份运行。

…即将“rmdir/q/s d:\temp\systmp\*”您可以使用语法错误停止它

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

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

HALT函数停止批处理文件,它使用自己的第二个函数,因此它可以通过重定向到nul来抑制语法错误的输出。您可以从
:not_sys_account
子例程设置
ERRORLEVEL
,并将其用作返回值。主程序可以检查并更改其行为:

@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/b1
现在指定了
ERRORLEVEL
,如果设置了
ERRORLEVEL
,则检查
if ERRORLEVEL 1 goto:eof
终止脚本。

!下次我需要的时候,我得试试这个。我通常在开头设置一个变量a,如:
fatalError=0
,然后在出现错误时将其设置为
fatalError=1
,并在从:calls返回时检查值。我喜欢这样,感谢您的想法。但我最终还是同意了乔恩,因为这种方法让我感觉更干净,因为将来会有其他人来维护它。