是否可以在PowerShell中对Compare-Object
又名diff
的数组中的项进行顺序比较?如果没有,建议解决方法。
$a1=@(1,2,3,4,5)
$b1=@(1,2,3,5,4)
if (Compare-Object $a1 $b1) {
Write-Host 'Wrong order '
}
else {
Write-Host 'OK'
}
答案 0 :(得分:1)
使用-SyncWindow 0
:
$a1=@(1,2,3,4,5)
$b1=@(1,2,3,5,4)
if (Compare-Object $a1 $b1 -SyncWindow 0) {
Write-Host 'Wrong order '
}
else {
Write-Host 'OK'
}
答案 1 :(得分:0)
您可以按值比较数组中的项目,如下所示:
$a1=@(1,2,3,4,5,6,7,8,9,10)
$b1=@(1,2,3,5,4,6,7,9,8,10)
$i= 0
$counter = 0
$obj = @()
foreach ($a in $a1)
{
$sub_obj = New-Object PSObject
$sub_obj | Add-Member -MemberType NoteProperty -Name Value1 -Value $a
$sub_obj | Add-Member -MemberType NoteProperty -Name Value2 -Value $b1[$i]
if ($a -eq $b1[$i])
{
$sub_obj | Add-Member -MemberType NoteProperty -Name IsMatch -Value $true
}
else
{
$sub_obj | Add-Member -MemberType NoteProperty -Name IsMatch -Value $false
$counter++
}
$obj += $sub_obj
$i++
}
Write-Output $obj | Format-Table -AutoSize
if ($counter -gt 0)
{Write-Host 'Wrong order!'}
else
{Write-Host 'Correct order!'}
<强>输出:强>
Value1 Value2 IsMatch
------ ------ -------
1 1 True
2 2 True
3 3 True
4 5 False
5 4 False
6 6 True
7 7 True
8 9 False
9 8 False
10 10 True
Wrong order!