Can't get errorlevel from failed MOVE command in batch script

user2844129 picture user2844129 · Oct 3, 2013 · Viewed 9.9k times · Source

I'm pretty new to this forum so i first want to thank you for providing me with solutions even before i became a member :).

So I have this code:

for %%a in ("%PBpath%") do ( 
move "network location 1 files" "network location 2" >NUL
if ERRORLEVEL 0 (echo Diagram %%~na.pdf was successfuly archived) else ( echo            Diagram %%~na.pdf was not archived )
ECHO.%errorlevel%
          )

The problem is that I can't get the errorlevel different than 0. Even when the files that are to be copied are missing from location, i still get the successfuly archived message echoed. I searched the forum for similar questions, but i couldn't make it work for some reason. Is there something different between the copy and the ping command (the ping command returns the correct exit code in the errorlevel), because i can't get it with either copy or move...

Thanks! Andrew

Answer

Superbob picture Superbob · Oct 3, 2013

The strange thing about the IF ERRORLEVEL statement is that it doesn't act like you expect- it returns TRUE if the errorlevel is equal to OR GREATER THAN the number specified. A failure in MOVE sets errorlevel to 1 (I just checked) which is greater than 0. Therefore the first clause in the IF statement will always be used. The easiest way to fix your script is to reverse the conditions in the IF statement:

if ERRORLEVEL 1 (echo file was not archived) else (echo file was successfully archived)