Don Alcombright
Don Alcombright

Reputation: 33

Get PowerShell to ignore exitcode?

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

Upvotes: 1

Views: 7065

Answers (2)

tibileo
tibileo

Reputation: 73

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
}

Upvotes: 4

Moerwald
Moerwald

Reputation: 11254

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.

Upvotes: 1

Related Questions