Batch Script not raising ERRORLEVEL on failure

两盒软妹~` 提交于 2021-01-27 16:00:27

问题


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?

My code is as below:

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

This is my output:

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:


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

to change errorlevel:

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


来源:https://stackoverflow.com/questions/31077490/batch-script-not-raising-errorlevel-on-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!