1

Im able to compare to arrays and get the index of an element, but this built in Compare-Object function is returning a strange value. When I run this code it returns the value of -1.

  1. How to compare two arrays are described here
  2. Get index of current item in powershell

This is my code.

# compare to arrays

$array1 = @(1,2,3,4,5)
$array2 = @(1,2,7,4,5)

$difference = Compare-Object $array1 $array2

# get the position of the difference in arrays
[array]::IndexOf($array1, $difference)
[array]::IndexOf($array2, $difference)

Result

PS C:\...\2017-06-25> C:\...\2017-06-25\compareArrays.ps1
-1
-1

Im going to use this to read to files and compare them and tell me where in the file the differences are.

Arne Bakke
  • 41
  • 6
  • Have you looked to see what object type `$difference` is, and what its structure and methods are? You might find that information edifying. Try `$difference.GetType()` and `$difference | Get-Member`. [`Get-Help Compare-Object`](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/compare-object) might also be useful and interesting – Jeff Zeitlin Jun 26 '17 at 18:33

2 Answers2

1

The issue is the output of Compare-Object does not match how you use it in IndexOf().

Compare-Object $array1 $array2

InputObject SideIndicator
----------- -------------
          7 =>
          3 <=

So what you are looking for is to split this into two separate arrays. One where it matches only on the left and one for the right. Using the Where method with Split makes this easy.

$RightDiffs,$LeftDiffs = $difference.where({$_.SideIndicator -eq "=>"},'Split')

In your example there is only one different in each, but potentially there will be multiple objects for each, so we'll need to loop over each object. And we'll want just the InputObject property.

foreach ($LeftDiff in $LeftDiffs.InputObject) {
    [array]::IndexOf($array1, $LeftDiff )
}
foreach ($RightDiff in $RightDiffs.InputObject) {
    [array]::IndexOf($array2, $RightDiff)
}
BenH
  • 9,766
  • 1
  • 22
  • 35
1

Perhaps something like

function Compare-Array {
  param(
    [Array] $array1,
    [Array] $array2
  )
  if ( -not (Compare-Object $array1 $array2) ) {
    return -1
  }
  for ( $i = 0; $i -lt $array1.Count; $i++ ) {
    if ( $array1[$i] -eq $array2[$i] ) {
      return $i
    }
  }
  return $array1.Length
}

Returns -1 if the arrays are equal or the index of the first difference between the two.

Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62