2013-10-08 45 views
1

如何在调用循环中完全停止批处理文件?在“call:loop”中完全停止批处理文件

exit /b仅仅退出:标签循环,而不是整个批处理文件,而裸exit离开批处理文件父CMD壳,这是不希望的。

@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! 

回答

1

您可以从: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 /b 1指定一个ERRORLEVEL如果ERRORLEVEL被设置检查if errorlevel 1 goto :eof终止脚本。

1

你可以用一个语法错误停止。

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

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

的暂停功能停止批处理文件,它使用自身,第二个功能,因此它可以通过重定向剿语法错误的输出到NUL

+0

棒极了!下次我需要时,我必须尝试一下。我通常设置一个变量开头,如:**'fatalError = 0' **,然后将其设置为** fatalError = 1 **,并检查返回值:calls。 –

+0

我喜欢这个,感谢这个想法。我最终给了乔恩点头,因为这种方法对我来说会更清洁,因为未来会有其他人维护。 –