Q & A: Capturing Robocopy Error Codes in PowerShell
Learn how you can capture robocopy error codes using PowerShell
February 24, 2016
Q: I’m writing a PowerShell script that calls robocopy to copy some directories. Since robocopy isn’t a PowerShell command it doesn’t return error codes in the PowerShell $error variable. How do I get return codes from command programs like robcopy?
A: Robocopy.exe is super useful program but it is external to PowerShell and doesn’t return errors like a PowerShell cmdlet. However, it does return an exit code upon completion. Since it is not a native PowerShell command its errors will not be captured in a standard PowerShell try-catch block or by using the $error collection. Fortunately, PowerShell provides the $LastExitCode variable that enables you to access the return codes from external programs. You can see an example in the following listing.
robocopy b:destinationdoesnotexist C:documents /MIR
if ($lastexitcode -eq 0)
{
write-host "Robocopy succeeded"
}
else
{
write-host "Robocopy failed with exit code:" $lastexitcode
}
When the robocopy process exits PowerShell will write the exit code to $LastExitCode variable. For most programs an exit code of 0 indicates success and 1 or greater indicates a failure. Robocopy is a bit different and can return any value between 1 and 7 and still be successful. You can see the robocopy return codes at: https://support.microsoft.com/en-us/kb/954404
Thanks to Keith Garner for sharing the reference to the Robocopy return codes.
About the Author
You May Also Like