Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows copy command return codes?

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 ... ) 
like image 857
Bill Ruppert Avatar asked Nov 21 '11 21:11

Bill Ruppert


People also ask

What does %1 mean in a batch file?

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.

How do you return a value from a batch file?

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.

What does errorlevel 1 mean?

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.


1 Answers

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.

like image 91
paxdiablo Avatar answered Oct 05 '22 17:10

paxdiablo