PowerShell order sensitive Compare-Objects diff

后端 未结 2 1862
说谎
说谎 2021-01-21 16:44

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

         


        
相关标签:
2条回答
  • 2021-01-21 17:18

    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!
    
    0 讨论(0)
  • 2021-01-21 17:30

    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.

    0 讨论(0)
提交回复
热议问题