Compare-Object gotcha

ISSUE

Compare-Object falsely reports some of the the same objects as being different.

For example, you compare two sets of objects:
$set1 = @(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
$set2 = @(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Compare-Object $set1 $set2

And see that the output falsely reports 1, 2, 14, and 15 being different (and in both sets.)

  InputObject SideIndicator
  ----------- -------------
           15 =>           
            1 <=           
           14 =>           
            2 <=           
            2 =>           
            1 =>           
           14 <=           
           15 <=           

CAUSE

The root of the issue is in the -SyncWindow parameter of Compare-Object. This parameter tells the cmdlet how far around to look to find the same element. By default it equals 5 – meaning that PowerShell will look at the item and plus/minus 5 elements around – which means that the defaults are good if you compare collections up to 11 elements. Anything bigger (as in our example) requires a bigger window (unless the collections are sorted).

RESOLUTION

Explicitly set sync window to half of the size of the smaller collection. In our case, the collections have 15 elements, so sync window should be set to 7:

Compare-Object $set1 $set2 -SyncWindow 7

This is a fairly frequent issue which people are facing for example when comparing group membership between different groups or a group and a CSV file.

Tags: , , ,

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




My Recent Tweets

Legal

The posts on this blog are provided “as is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer - WSO2 or anyone else for that matter. All trademarks acknowledged.

© 2007-2014 Dmitry Sotnikov

June 2008
M T W T F S S
« May   Jul »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Follow

Get every new post delivered to your Inbox.

Join 93 other followers

%d bloggers like this: