Back to Basics: Comparing Property Values Between PS Custom Objects
You have two PS custom objects. They contain the same property names. You want to compare the values of each of the properties, i.e. does the value of property 1 from PS custom object A match the value of property 1 from PS custom object B, does the value of property 2 from PS custom object A match the value of property 2 from PS custom object B, and so on?
As always, with PowerShell there's many ways to 'skin a cat' (achieve the same objective).
$a = [pscustomobject]@{
test1 = "a"
test2 = "b"
test3 = "c"
test4 = "d"
test5 = "e"
}
$b = [pscustomobject]@{
test1 = "a"
test2 = "b"
test3 = "z"
test4 = "d"
test5 = "bobo"
}
$a_props = $a.psobject.Properties.Name
foreach ($a_prop in $a_props) {
$comp = Compare-Object -ReferenceObject $a -DifferenceObject $b -Property $a_prop -IncludeEqual
if ($comp.sideindicator -eq "==") {
"$($comp.psobject.Properties.name[0]) - the same"
}
else {
"$($a_prop) - different"
}
}
Man, that's a lot of code for one of my posts!
What's going on? Well, first up we create two PS custom objects, both with the same property names, but with a slight variation in values.
Next, get a list of the property names from the first object.
Loop through these property names and perform Compare-Object using the current property name, comparing the respective values from PS custom object A and PS custom object B.
Output where we have a match and where we have a deviation.