首页 文章

批处理脚本在失败时不会引发ERRORLEVEL

提问于
浏览
3

我正在学习Windows批处理脚本 . 复制,移动或删除操作失败时,我需要引发错误 . 我制作了一个示例脚本,由于某种原因,当操作失败时,我无法使ERRORLEVEL上升 . 我运行脚本,文件不存在或在另一个程序中打开,stderr消息输出到控制台,但ERRORLEVEL永远不会上升,为什么会这样?另外,有没有办法将stderr管道输入我可以检查的变量,如果我不能让ERRORLEVEL上升?

我的代码如下:

`@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

1 回答

  • 2

    DEL 命令不会更改errorlevel - more info检查debenham建议以检测失败的删除:

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

    改变errorlevel:

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

相关问题