在For循环中退出 - Windows命令处理器(CMD.EXE) [英] Exit in For loop - Windows Command Processor (CMD.EXE)

查看:2588
本文介绍了在For循环中退出 - Windows命令处理器(CMD.EXE)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到方法打破/退出FOR循环,如果有任何错误发生。
以下是批处理文件的内容。

I am trying to find way to break / exit from FOR loop, if there are any error occured. Below is content of batch file.

@echo on

set myfile=D:\sample.txt

FOR /F "tokens=1,2 delims=," %%i in (%myfile%) do call :process "%%i"

:process
set recfile=%1%

echo %recfile%
echo "Step in Test1"
echo %errorlevel%
pause;

exit /B 0
If %errorlevel% NEQ 0 goto :fail1

:fail1
echo "Step in fail1"
pause;
exit /B 9993

:EOF

Sample.txt有多个记录。如果发生任何错误,我希望退出批处理文件,而不是检查完整的sample.txt文件。例如on语句
echo%recfile%,如果我放错命令ech%recfile%这是不正确的命令,那么我期望它应该去fail1级别并退出。它成功的catured错误代码成功,并进入fail1级别,但是在这个状态后,它再次检查sample.txt文件(下一个记录)。有什么办法,如果我可以打破/退出FOR循环。

Sample.txt has multiple records. If there are any error occured then I am expecting to exit the batch file rather then checking the complete sample.txt file. e.g. on statement echo %recfile%, If I place some wrong command ech %recfile% which is incorrect command then I am expecting that it should go to fail1 level and exit. It's catured the error code successfully and going to fail1 level however after this statment, it's checking the sample.txt file (next record) again. Is there any way, If I can break / exit FOR loop.

请咨询。

/ p>

Thanks,

推荐答案

Joey的答案是很好的。我用它成功了。我发现你不必退出脚本。您可以使用 goto:SomeLabel ,其中:SomeLabel 是循环外的标签。

Joey's answer is great. I have used it with success. I discovered that you don't have to exit the script though. You can use goto :SomeLabel, where :SomeLabel is a label outside of the loop.


FOR /F "tokens=1,2 delims=," %%i in (%myfile%) do (
  if defined exit goto :ParseError
  call :process "%%i"
)

@echo SUCCESS: %myfile%
goto :RestOfScript

:ParseError
@echo FAILURE: cannot parse %myfile%
@echo Using defaults...

:RestOfScript
...

这篇关于在For循环中退出 - Windows命令处理器(CMD.EXE)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆