1

I am using robocopy within PowerShell and robocopy returns an exitcode 1 if a file has successfully been copied, which tells PowerShell it failed. Is there a good practice to ignore the error since its not an error?

$source = "$env:buildlocation\Reports\$env:ctrelname\DiskImages\DISK1";
$target = "$env:builddestination\$env:ctrelver\$env:ctrelname\Reports";
$robocopyOptions = @('/e', '/r:0', '/np');
Get-ChildItem -Path $source -Directory -Attributes !Hidden |
    Sort-Object -Property CreationTime |
    ForEach-Object { & robocopy.exe $source $target $robocopyOptions };
echo $LASTEXITCODE
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • See [this question](http://stackoverflow.com/questions/13883404/custom-robocopy-progress-bar-in-powershell) for instance. – sodawillow Feb 10 '17 at 19:41
  • 1
    Why would you need that? Exit codes from external commands don't matter to PowerShell unless you explicitly handle the exit code. – Ansgar Wiechers Feb 11 '17 at 11:36

2 Answers2

4

I've encountered the same situation when using robocopy from a PowerShell script run by Jenkins; and in this case, it is mandatory to clear LASTEXITCODE, because Jenkins checks for it at the end of the job and your job will fail (excluding of course the case where you have another external command called after robocopy that clears the last exit code.

I've used this code:

$initialExitCode = $global:LASTEXITCODE
Invoke-Expression "robocopy ..."
# See robocopy exit codes: if it's less than 8, there should be no terminal error
if (($initialExitCode -eq 0 -or [string]::IsNullOrWhiteSpace($initialExitCode)) -and $LASTEXITCODE -le 7) {
    $global:LASTEXITCODE = 0
}
tibileo
  • 73
  • 1
  • 9
1

As stated above PowerShell doesn't evaluate the error code of a native command. It only stores it in $LastExitCode. Try this simple example:

Invoke-Expression 'cmd /c "exit 5"'

PowerShell only stores 5 in $LastExitCode.

Moerwald
  • 10,448
  • 9
  • 43
  • 83