批处理脚本在失败时未引发ERRORLEVEL [英] Batch Script not raising ERRORLEVEL on failure

查看:74
本文介绍了批处理脚本在失败时未引发ERRORLEVEL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Windows批处理脚本.复制,移动或删除操作失败时,我需要提出错误.我制作了一个示例脚本,由于某种原因,当操作失败时,我无法使ERRORLEVEL升高.我运行脚本,文件不存在或在另一个程序中打开,并且stderr消息输出到控制台,但是ERRORLEVEL从不上升,这是为什么?另外,如果无法使ERRORLEVEL上升,是否有任何方法可以将stderr传递给我可以检查的变量?

I am learning Windows batch scripting. I need to raise errors when copy, move or delete operations fail. I have made a sample script and for some reason, when the operation fails I cannot get the ERRORLEVEL to rise. I run the script and the files either do not exist or are opened in another program and stderr messages are output to console, but ERRORLEVEL never rises, why is this? Also, is there any way to pipe stderr into a variable I could check, if I cannot get ERRORLEVEL to rise?

我的代码如下:

`@Echo Off
ECHO.
Set /P myVar=Please enter a value:
Echo var = %myVar%
ECHO Trying to delete the file dummy.csv >> log.txt
Set myVar2 = nothing
DEL C:\dummy420.csv  
IF NOT ERRORLEVEL 0 ECHO There was an error
ECHO %ERRORLEVEL%
REM 2>myVar2
REM Echo 2>
REM Echo %myVar2%
Echo 2>&1
REM && (echo yourCommand was successful) || (echo yourCommand failed)
IF NOT ERRORLEVEL 0 ECHO There was an error
ECHO %ERRORLEVEL%
Move ""C:\dummy420.csv" D:\"
IF NOT ERRORLEVEL 0 ECHO There was an error
Set /P dummy=Press Enter to End`

这是我的输出:

Please enter a value:hello
var = hello
C:\dummy420.csv
The process cannot access the file because it is being used by another process.
0
ECHO is off.
0
The filename, directory name, or volume label syntax is incorrect.
Press Enter to End

推荐答案

DEL 命令不会更改错误级别-

DEL command does not change the errorlevel - more info Check the debenham suggestion to detect failed deletion:

3>&2 2>&1 1>&3 del C:\dummy420.csv|findstr . && echo DEL failed || echo DEL succeeded

更改错误级别:

3>&2 2>&1 1>&3 del C:\dummy420.csv|findstr .&& cmd /c exit /b 1

这篇关于批处理脚本在失败时未引发ERRORLEVEL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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