Search code examples
arrayspowershellcomparecompareobject

Compare-Object Returning Invalid Results


First post to stackoverflow so apologies in advance if I miss a social norm.

I have an array in PowerShell that holds thousands of objects in it. Standard stuff with each object having properties such as username, login times, computer they logged into, etc. I then split off a small number of objects from the first array with users whose name starts with A:

$Array2 = $Array1 | where-object Username -like '*\a*'

This works as expected.

I want to build a third array that only contains the objects from $Array1 that are not in $Array2. Or in other words an array with only users whose usernames do not start with A. This seems like the way to go:

$Array3 = compare-object $Array1 $Array2 | select-object -expandproperty InputObject

Expectation:

$Array3 | where-object Username -like '*\a*'

results in a nothing returned

What I'm getting though are plenty of results. Strangely if I look at the .count of each array the math works out. Array1 minus Array2 equals Array3. So it is removing the correct number of objects, just not the expected objects. What am I doing wrong here? Since I'm doing a pull from the exact array I'm comparing against I can't think of any other criteria it would be searching for that would return an unexpected match. I also tried sorting each array by the same property before comparing because I was grasping but as expected that didn't fix it.

Thanks in advance!


Solution

  • My conclusion is that some commandlets build arrays in such a way that it breaks compare-object. I'm still unsure as to what this mysterious "way" is, but the problem presents itself when using Citrix's Get-BrokerSession and does not when using Get-AdUser.

    Long answer For those really wanting to use compare-object here is the way I got it to work:

    compare-object $Array1 $Array2 -Property Username -PassThru

    With the -PassThru being the eureka moment for me.

    My question was specifically about how/why compare-object wasn't working the way I expected. All answers, to my interpretation, only provided different ways to work around the problem and didn't actually answer the question. Special thanks to @js2010 for continuing to work with me through it.