如何在遇到错误时终止批处理文件?

编程入门 行业动态 更新时间:2024-10-27 12:29:16
本文介绍了如何在遇到错误时终止批处理文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个批处理文件,它使用不同的参数一遍又一遍地调用同一个可执行文件.如果其中一个调用返回任何级别的错误代码,如何使其立即终止?

I have a batch file that's calling the same executable over and over with different parameters. How do I make it terminate immediately if one of the calls returns an error code of any level?

基本上,我想要相当于 MSBuild 的 ContinueOnError=false.

Basically, I want the equivalent of MSBuild's ContinueOnError=false.

推荐答案

检查if语句中的errorlevel,然后exit/b(仅退出 batch 文件,而不是整个 cmd.exe 进程)对于 0 以外的值.

Check the errorlevel in an if statement, and then exit /b (exit the batch file only, not the entire cmd.exe process) for values other than 0.

same-executable-over-and-over.exe /with different "parameters" if %errorlevel% neq 0 exit /b %errorlevel%

如果您希望 errorlevel 的值传播到您的批处理文件之外

If you want the value of the errorlevel to propagate outside of your batch file

if %errorlevel% neq 0 exit /b %errorlevel%

但是如果这是在 for 中,它会变得有点棘手.你需要更多类似的东西:

but if this is inside a for it gets a bit tricky. You'll need something more like:

setlocal enabledelayedexpansion for %%f in (C:Windows*) do ( same-executable-over-and-over.exe /with different "parameters" if !errorlevel! neq 0 exit /b !errorlevel! )

您必须在每个命令之后检查错误.在 cmd.exe/command 批处理中没有全局的on error goto"类型的构造.我还根据 CodeMonkey 更新了我的代码,尽管我从未在任何批量黑客攻击中遇到过负面错误级别在 XP 或 Vista 上.

You have to check the error after each command. There's no global "on error goto" type of construct in cmd.exe/command batch. I've also updated my code per CodeMonkey, although I've never encountered a negative errorlevel in any of my batch-hacking on XP or Vista.

更多推荐

如何在遇到错误时终止批处理文件?

本文发布于:2023-10-16 00:42:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1495968.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:批处理文件   错误   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!