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
2
  • See this question for instance. Commented Feb 10, 2017 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. Commented Feb 11, 2017 at 11:36

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.