“第"当删除失败等错误时退出错误级别设置为 0 [英] "rd" exits with errorlevel set to 0 on error when deletion fails, etc
问题描述
我正在编写一个批处理 (.bat) 脚本,我需要处理文件夹删除失败的情况.我正在使用 %errorlevel%
来捕获退出代码,但在 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:UsersedoDesktop>rd testdir
Directory is not empty
C:UsersedoDesktop>echo %errorlevel%
0
为什么?你有什么建议?
Why? What do you suggest?
推荐答案
哇,这是我见过的 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.所以你甚至不需要做任何事情.您可以有条件地执行"一个注释,然后错误级别将被正确设置.
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%
<小时>
我以为上面给出了一个完整的图片.但是下面的一系列评论表明,在使用 /RD/S
时仍然存在潜在问题.如果父文件夹下的文件或子文件夹被锁定(在父文件夹下的任何级别),则 RD/S/Q PARENT &&回声已删除 ||echo failed
将打印出错误消息,但是 &&
分支会触发,而不是 ||
分支.很不幸.如果由于父文件夹本身被锁定而导致命令失败,则 ||
将正确触发并设置 ERRORLEVEL.
I thought the above gave a complete picture. But then a series of comments below demonstrated there are still potential problems when /RD /S
is used.
If a file or subfolder under the parent folder is locked (at any level under parent) then RD /S /Q PARENT && echo removed || echo failed
will print out an error message, but the &&
branch fires instead of the ||
branch. Very unfortunate. If the command fails because the parent folder itself is locked, then ||
will properly fire and set the ERRORLEVEL.
通过将 stderr 与 stdout 交换并将结果传送到 FINDSTR "^"
,可以在所有情况下检测失败.如果找到匹配项,则一定有错误.
It is possible to detect failure in all cases by swapping stderr with stdout and piping the result to FINDSTR "^"
. If a match is found, then there must have been an error.
3>&2 2>&1 1>&3 rd /s test | findstr "^" && echo FAILED
当 /q
缺失时,stderr 和 stdout 的交换很重要,因为它允许你确定(是/否)吗?"提示在 stderr 上可见,与 stdout 上的错误消息分开.
The swap of stderr and stdout is important when /q
is missing because it allows the "Are you sure (Y/N)?" prompt to be visible on stderr, separate from the error message on stdout.
这篇关于“第"当删除失败等错误时退出错误级别设置为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!