2013-10-08 43 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

我喜歡這個,感謝這個想法。我最終給了喬恩點頭,因爲這種方法對我來說會更清潔,因爲未來會有其他人維護。 –