Using robocopy with Visual Studio 2010 Post-build and Pre-build events

Adding this answer per request. Based on Asaf's solution, and adding skrebbel's comment.

You can simplify the check to:

robocopy <opt> <src> <tgt>
if %errorlevel% leq 1 exit 0 else exit %errorlevel%

As kindly remarked in the comments, you may want to adjust the '1': It depends on what your operation should treat as an error. Have a look at the meaning of the bits that in combination make up the number returned by robocopy:

0×10 Serious error. Robocopy did not copy any files. This is either a usage error or an error due to insufficient access privileges on the source or destination directories.

0×08 Some files or directories could not be copied (copy errors occurred and the retry limit was exceeded). Check these errors further.

0×04 Some Mismatched files or directories were detected. Examine the output log. Housekeeping is probably necessary.

0×02 Some Extra files or directories were detected. Examine the output log. Some housekeeping may be needed.

0×01 One or more files were copied successfully (that is, new files have arrived).

0×00 No errors occurred, and no copying was done. The source and destination directory trees are completely synchronized.


Simply checking for an exit code of 1 is incorrect, as any exit code below 8 is non-erroneous:

Any value greater than 8 indicates that there was at least one failure during the copy operation.

(Just to clarify, an exit code of 8 is an error as well: Several files did not copy)

The proper code, then, should look like this:

IF %ERRORLEVEL% GEQ 8 exit 1
exit 0

With <src>, <tgt> being the copy source and target respectfully, and <opt> being robocopy options:

robocopy <opt> <src> <tgt>
set rce=%errorlevel%
if not %rce%==1 exit %rce% else exit 0

For instance, if we want to copy the project target to c:\temp, without retries and with all sub-directories (empty or not), we'd use:

robocopy /R:0 /E $(TargetDir) c:\temp
set rce=%errorlevel%
if not %rce%==1 exit %rce% else exit 0