PowerShell顺序敏感的比较对象差异

时间:2016-11-09 12:55:38

标签: powershell

是否可以在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' 
}

2 个答案:

答案 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' 
}

更多信息:Comparing Arrays in Windows PowerShell

答案 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!