我无法解决这个按位转换问题。

Robocopy exit codes不符合正常的0(成功),1(失败)模式,因此我想将我的robocopy调用包装在下面的powershell脚本中,以使我的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)

最佳答案

在您的情况下,您无需转换它。
您不需要进行转换,因为哈希表键在预补偿阶段已转换为[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)

关于Powershell按位比较Robocopy退出代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21428632/

10-11 16:50