windows - 在 "call :loop"中完全停止批处理文件

标签 windows batch-file

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

exit/b 只是退出 :label 循环,而不是整个批处理文件,而 bare 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!

最佳答案

您可以从 :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 并且检查 if errorlevel 1 goto :eof 终止设置了 ERRORLEVEL 时的脚本。

关于windows - 在 "call :loop"中完全停止批处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258020/

相关文章:

java - 来自不同 Java 线程的 JNI native 调用是否按顺序进行?

python - 如何使用 Python 检查文件保存是否完成?

javascript - node js 在 pc 上抛出错误,但在 Ubuntu 上不抛出错误

.net - 如何使用 .Net 命令提示符强制启动和运行 .bat 文件

windows - 通过cmd/batch/powershell启用Windows 10内置热点

c++ - 为什么 Windows 上的套接字描述符会得到这样的值?

c - Windows 驱动程序开发的良好资源

windows - 如何让vba文件自行删除

batch-file - Batch if form with ( do ( 在里面?

java - 批处理文件如何接受 Java 的参数?