Skip to content

Instantly share code, notes, and snippets.

@jonathancounihan
Created October 7, 2016 10:37
Show Gist options
  • Save jonathancounihan/1d2ad2853c6aaa01e7f642cfcf58eac4 to your computer and use it in GitHub Desktop.
Save jonathancounihan/1d2ad2853c6aaa01e7f642cfcf58eac4 to your computer and use it in GitHub Desktop.
Robocopy From powershell
function InvokeRoboCopyCommandWithErrorChecking ($command, $errorMessage) {
$global:LASTEXITCODE = 0
[int[]]$errorCodes = @(8,16)
#Write-Host $command
Invoke-Expression $command -ErrorAction Stop
$roboCopyExitCode = $global:LASTEXITCODE;
# Below is taken from http://stackoverflow.com/questions/21428632/powershell-bitwise-comparison-for-robocopy-exit-codes
$returnCodeMessage = @{
0x00 = "[ROBOCOPY - INFO]: No errors occurred, and no copying was done. The source and destination directory trees are completely synchronized."
0x01 = "[ROBOCOPY - INFO]: One or more files were copied successfully (that is, new files have arrived)."
0x02 = "[ROBOCOPY - INFO]: Some Extra files or directories were detected. Examine the output log for details."
0x04 = "[ROBOCOPY - WARN]: Some Mismatched files or directories were detected. Examine the output log. Some housekeeping may be needed."
0x08 = "[ROBOCOPY - ERROR]: Some files or directories could not be copied (copy errors occurred and the retry limit was exceeded). Check these errors further."
0x10 = "[ROBOCOPY - ERROR]: Usage error or an error due to insufficient access privileges on the source or destination directories."
}
Write-Host $( @( $returnCodeMessage.Keys | Where-Object { $_ -band $roboCopyExitCode } | ForEach-Object {return $returnCodeMessage[$_]} ) -join "`r`n");
$global:LASTEXITCODE = ($roboCopyExitCode -ge 8); # Change it to something other systems will understand
if ($PSVersionTable.PSVersion.Major -ge 3) {
if ($errorCodes.Contains($roboCopyExitCode)) {
throw $errorMessage
}
}
else {
$errorCodes | foreach {
if ($_ -eq $roboCopyExitCode) {
throw $errorMessage
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment