Sometimes, you write a script that uses robocopy to copy or move files around efficiently, and you need to confirm that no errors occurred during robocopy’s run. Unfortunately, robocopy doesn’t use the standard error return mechanism of 0 for no errors and 1 (or some other non-zero number) if an error occurred. Microsoft documents robocopy exit codes in KB 954404, but the information isn’t complete. A better explanation can be found in a Deployment Guys blog post and shows that the exit codes are bitmapped:
Code | Meaning |
0 | No errors occurred and no files were copied. |
1 | One of more files were copied successfully. |
2 | Extra files or directories were detected. Examine the log file for more information. |
4 | Mismatched files or directories were detected. Examine the log file for more information. |
8 | Some files or directories could not be copied and the retry limit was exceeded. |
16 | Robocopy did not copy any files. Check the command line parameters and verify that Robocopy has enough rights to write to the destination folder. |
These codes are combined to give a complete indication of the results of the run. For example, if the exit code is 3, that indicates that files were copied successfully and that extra files or directories were detected (1 + 2 = 3). The important conclusion is to note that any return code with 0x8 or 0x16 set indicates that some or all of the files were not copied.
To decode these exit codes in Powershell, use the bitwise and operator –band to test for the bits we are interested in. In binary, the important bits are 011000, which converts to decimal 24. So, you can do your robocopy operation like this:
$cmd_args = @($source, $target, $action, $options) & robocopy.exe @cmd_args If ($LastExitCode -band 24) { Write-Host “Everything is OK” } else { Write-Host “Errors happened” }