Given you are comparing complex objects. I don't think Compare-Object is the right tool. When using the -Property parameter Compare-Object will strip the original input objects from it's output objects. -PassThru will amend the input objects with the SideIndicator property, but it will not include data from both the objects for whom the given property was equivalent. In cases where other property values differ it will not be represented in the output.
$ObjectArray1 =
@(
[PSCustomObject]@{
Birth_Date = [DateTime]'4/22/65'
FirstName = "Otto"
Object_id = 1234
}
[PSCustomObject]@{
Birth_Date = [DateTime]'5/30/67'
FirstName = "Jean"
Object_id = 9999
}
)
$ObjectArray2 =
@(
[PSCustomObject]@{
Birth_Date = [DateTime]'4/1/80'
FirstName = "Bob"
Object_id = 1234
}
[PSCustomObject]@{
Birth_Date = [DateTime]'5/30/67'
FirstName = "Jean"
Object_id = 9998
Prop4 = "Some other val"
}
)
Compare-Object $ObjectArray1 $ObjectArray2 -IncludeEqual -ExcludeDifferent -Property FirstName -PassThru
This returns
Birth_Date FirstName Object_id SideIndicator
---------- --------- --------- -------------
5/30/1967 12:00:00 AM Jean 9999 ==
Notice there's only 1 object. There's no indication of Prop4, nor that the second object had a different Object_id. Only the reference object is output.
Something like below would reveal such differences.
$Output = [Collections.ArrayList]@()
$ObjectArray1 |
ForEach-Object{
If( $_.FirstName -in $ObjectArray2.FirstName ) {
[Void]$Output.Add($_)
}
}
$ObjectArray2 |
ForEach-Object{
If( $_.FirstName -in $ObjectArray1.FirstName ) {
[Void]$Output.Add($_)
}
}
$Output
Output:
Birth_Date FirstName Object_id
---------- --------- ---------
5/30/1967 12:00:00 AM Jean 9999
5/30/1967 12:00:00 AM Jean 9998
I suppose it depends on the nature of the objects and tables. However, it strikes me that operators like -contains & -on it just strikes me that are better options.
It would be even easier if when the first name is the same all other properties are the same. Essentially you would only need to output from one of the collections:
$ObjectArray1 =
@(
#...
[PSCustomObject]@{
Birth_Date = [DateTime]'5/30/67'
FirstName = "Jean"
Object_id = 9999
}
)
$ObjectArray2 =
@(
# ...
[PSCustomObject]@{
Birth_Date = [DateTime]'5/30/67'
FirstName = "Jean"
Object_id = 9999
}
)
$ObjectArray1 |
Where-Object{ $_.FirstName -in $ObjectArray2.FirstName }
$Nameyou are using it as an argument to-IncludeProperty. Doing this will expand the variable's value in that spot when it looks like you want the name of the property. It looks like you're doing the same thing with theSelect-Objectcommand. Unless that's intentional and those are defined elsewhere.