机器人退出代码的Powershell按位比较

时间:2014-01-29 10:44:02

标签: powershell bit-manipulation hex

我无法理解这种按位转换问题。

Robocopy exit codes不符合正常的0(成功),1(失败)模式,因此我想在下面的powershell脚本中包含我的robocopy调用,以使我的TeamCity构建配置失败或在robocopy时正确进行终止。

第一部分是使用tip from the net解决的:($LastExitCode -band 24)正确地将退出代码8到16视为失败(1),将所有其他代码视为成功(0)。

现在我想回显一个与退出代码对应的消息。如何将整数退出代码(0 - 16)转换和舍入/舍入为其十六进制等效值(0x00 - 0x10)?

param(
    [string] $source,
    [string] $target,
    [string[]] $action = @("/MIR"),
    [string[]] $options = @("/R:2", "/W:1", "/FFT", "/Z", "/XA:H")
)
$cmd_args = @($source, $target, $action, $options)
& robocopy.exe @cmd_args
$returnCodeMessage = @{
    0x00 = "[INFO]: No errors occurred, and no copying was done. The source and destination directory trees are completely synchronized."
    0x01 = "[INFO]: One or more files were copied successfully (that is, new files have arrived)."
    0x02 = "[INFO]: Some Extra files or directories were detected. Examine the output log for details."
    0x04 = "[WARN]: Some Mismatched files or directories were detected. Examine the output log. Some housekeeping may be needed."
    0x08 = "[ERROR]: Some files or directories could not be copied (copy errors occurred and the retry limit was exceeded). Check these errors further."
    0x10 = "[ERROR]: Usage error or an error due to insufficient access privileges on the source or destination directories."
}
Write-Host $returnCodeMessage[($LastExitCode <what goes here?>)]
exit ($LastExitCode -band 24)

2 个答案:

答案 0 :(得分:2)

在您的情况下,您不需要转换它。 您不需要转换,因为Hashtable键在预编译阶段转换为[int]。 如果查找$ returnCodeMessage.Keys,您将看到十进制数字,而不是十六进制数字

显示您应该使用的所有邮件

$exitcode = $LastExitCode    
Write-Host $( @( $returnCodeMessage.Keys | Where-Object { $_ -band $exitcode } | ForEach-Object {return $returnCodeMessage[$_]}   ) -join "`r`n")

如果要显示十六进制编码的$ LastExitCode,请执行

$exitcode = $LastExitCode
Write-Host $('0x' + [System.Convert]::ToString([int]$exitcode,[int]16) )
return $exitcode

String System.Convert.ToString(Int32, Int32)

答案 1 :(得分:1)

作为filimonic mentioned0x1016只是编写相同基础数值的不同方式(即0x10 -eq 16计算为true),所以没有转换是必要的。

要在组合返回代码中显示每条消息,您可以依次测试每个单独的标志值:

if( $returnCodeMessage.ContainsKey( $LastExitCode ) ) {
    $returnCodeMessage[$LastExitCode]
}
else {
    for( $flag = 1; $flag -le 0x10; $flag *= 2 ) {
        if( $LastExitCode -band $flag ) {
            $returnCodeMessage[$flag]
        }
    }
}

对于仅包含一条消息的0x00(无更改)或0x04(不匹配)等返回代码,我们会直接查找。否则,对于复合代码,如0x09(有些复制,有些没有)或0x13(有些复制,有些额外,访问被拒绝),我们检查每种可能性并输出匹配的。

此外,由于“任何大于8的值表示复制操作期间至少有一次失败”,您可以使用$LastExitCode -ge 8代替$LastExitCode -band 24来测试错误。