I would like to test for the success/failure of a copy in a batch file, but I can't find any documentation on what if any errorlevel codes are returned. For example
copy x y if %errorlevel%. equ 1. ( echo Copy x y failed due to ... exit /B ) else ( if %errorlevel% equ 2. ( echo Copy x y failed due to ... exit /B ) ... etc ... )
When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.
Syntax. It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file. EXIT /B at the end of the batch file will stop execution of a batch file. Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.
In Microsoft Windows and MS-DOS, an errorlevel is the integer number returned by a child process when it terminates. Errorlevel is 0 if the process was successful. Errorlevel is 1 or greater if the process encountered an error.
I'd opt for xcopy
in this case since the error levels are documented (see xcopy documentation, paraphrased below):
Exit code Description ========= =========== 0 Files were copied without error. 1 No files were found to copy. 2 The user pressed CTRL+C to terminate xcopy. 4 Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line. 5 Disk write error occurred.
In any case, xcopy
is a far more powerful solution. The equivalent documentation for copy
does not document the error levels.
As an aside, you may want to rethink your use of the %errorlevel%
variable. It has unexpected results, at least in some versions of Windows, if someone has explicitly done something silly like:
set errorlevel=22
In those cases, the actual variable will be used rather than grabbing the actual error level. The "normal" way of doing this is (in decreasing order since errorlevel
is a "greater than or equal to" check):
if errorlevel 2 ( echo Copy x y failed due to reason 2 exit /B ) if errorlevel 1 ( echo Copy x y failed due to reason 1 exit /B )
In addition, if you are running Win7 or Win Server 2008 or later, you should look into Robocopy, which is now the preferred mass-copy solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With