PowerShell order sensitive Compare-Objects diff

≡放荡痞女 提交于 2021-01-20 07:55:54

问题


Is it possible to do the order comparison of items in arrays with Compare-Object aka diff in PowerShell? if not, suggest a workaround.

$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' 
}

回答1:


Use -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' 
}

More info: Comparing Arrays in Windows PowerShell.




回答2:


You could compare items in arrays value by value, like this:

$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!'}

Output:

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!


来源:https://stackoverflow.com/questions/40507552/powershell-order-sensitive-compare-objects-diff

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!