让PowerShell忽略exitcode?

时间:2017-02-10 18:00:05

标签: powershell exit-code

我在PowerShell中使用robocopy,如果文件成功复制,robocopy会返回一个exitcode 1,这会告诉PowerShell它失败了。是否有一个很好的做法可以忽略错误,因为它不是错误?

$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 个答案:

答案 0 :(得分:0)

如上所述,PowerShell不会评估本机命令的错误代码。它只将其存储在$LastExitCode中。试试这个简单的例子:

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

PowerShell仅在$LastExitCode中存储5个。

答案 1 :(得分:0)

Jenkins 运行的 PowerShell 脚本中使用 robocopy 时,我遇到了相同的情况;并且在这种情况下,强制性清除 LASTEXITCODE 是强制性的,因为詹金斯会在工作结束时进行检查,并且您的工作将会失败(当然,如果您在 robocopy 之后还有另一个外部命令被调用,它清除了最后一个退出代码。

我使用了以下代码:

$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
}
相关问题