批:退出code为" RD"在误差为0,以及 [英] batch: Exit code for "rd" is 0 on error as well

查看:237
本文介绍了批:退出code为" RD"在误差为0,以及的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个批处理(.bat)脚本,我需要处理,其中一个文件夹的删除失败的情况下。我使用%ERRORLEVEL%赶出境code,但在 RD的情况下命令它似乎不工作:

I'm writing a batch (.bat) script and I need to handle the case in which the deletion of a folder fails. I'm using %errorlevel% to catch the exit code, but in the case of the rd command it seems not to work:

C:\Users\edo\Desktop>rd testdir
Directory is not empty

C:\Users\edo\Desktop>echo %errorlevel%
0

为什么呢?你有什么建议?结果
谢谢!

Why? What do you suggest?
Thanks!

推荐答案

哇,这是我见过的第二个情况ERRORLEVEL没有设置正确!请参见文件重定向在Windows和%ERRORLEVEL%

Wow, this is the 2nd case I've seen where ERRORLEVEL is not set properly! See File redirection in Windows and %errorlevel%.

的解决方案是一样用于检测重定向失败。使用 || 运营商采取在失败的行动。

The solution is the same as for detecting redirection failure. Use the || operator to take action upon failure.

rd testdir || echo The command failed!

在离奇的事情是,当你使用 || 运算符,ERRORLEVEL然后正确设置为145,如果该文件夹不为空,或者2如果文件夹没有不存在。所以,你甚至不需要做任何事情。你可以有条件地执行一听这话,并且ERRORLEVEL将被正确设置。

The bizarre thing is, when you use the || operator, the ERRORLEVEL is then set properly to 145 if the folder was not empty, or 2 if the folder did not exist. So you don't even need to do anything. You could conditionally "execute" a remark, and the errorlevel will then be set properly.

rd testdir || rem
echo %errorlevel%

更新2016年1月21日

早在2015年四月,安德烈亚斯Vergison中声称评论|| 没有设置为拒绝访问,或者ERRORLEVEL ......在使用。 ..的错误。我的Windows 7的时候,我不认为我验证了他的说法,只是认为他是正确的。但我已经在Windows 10最近测试,而 || 总是在错误设置ERRORLEVEL为非零。需要注意的是(呼叫)是迫使ERRORLEVEL为0,我每次运行命令之前的神秘方式。另外请注意,我的CMD.EXE会议已经推迟扩张启用。

Back in April of 2015, Andreas Vergison claimed in a comment that || did not set the ERRORLEVEL for "Access Denied", or "...In Use..." errors. I had Windows 7 at the time, and I don't think I verified his claim, but just assumed he was correct. But I have recently tested in Windows 10, and the || always sets the ERRORLEVEL to non-zero upon error. Note that (call ) is an arcane way of forcing the ERRORLEVEL to 0 before I run each command. Also note that my cmd.exe session has delayed expansion enabled.

C:\test>(call ) & rd junk && echo OK || echo ERROR !errorlevel!
Access is denied.
ERROR 5

C:\test>(call ) & rd test && echo OK || echo ERROR !errorlevel!
The directory is not empty.
ERROR 145

C:\test>(call ) & rd \test && echo OK || echo ERROR !errorlevel!
The process cannot access the file because it is being used by another process.
ERROR 32

C:\test>(call ) & rd notExists && echo OK || echo ERROR !errorlevel!
The system cannot find the file specified.
ERROR 2

这篇关于批:退出code为" RD"在误差为0,以及的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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