PowerShell Comparing Objects
Comparing objects is finding the differences between two lists. It shows which items sit in only one list and which sit in both.
Find items in only one list
Without -IncludeEqual, only the differences print. Each line shows the item and where it sits.
$left = @('apple', 'banana', 'cherry')
$right = @('banana', 'cherry', 'date')
$diff = Compare-Object $left $right | Sort-Object InputObject
foreach ($d in $diff) { $d.InputObject + ': ' + $d.SideIndicator }Include the items in both lists
Add -IncludeEqual to keep the shared items too. Shared items print with ==.
$left = @('apple', 'banana', 'cherry')
$right = @('banana', 'cherry', 'date')
$diff = Compare-Object $left $right -IncludeEqual | Sort-Object InputObject
foreach ($d in $diff) { $d.InputObject + ': ' + $d.SideIndicator }Compare objects by one property
Use -Property Name so objects match on their Name alone. Each line shows the name and where it sits.
$leftObj = @(
[PSCustomObject]@{Name='apple'; Price=2}
[PSCustomObject]@{Name='pear'; Price=3}
)
$rightObj = @(
[PSCustomObject]@{Name='apple'; Price=2}
[PSCustomObject]@{Name='plum'; Price=4}
)
$diff = Compare-Object $leftObj $rightObj -Property Name | Sort-Object Name
foreach ($d in $diff) { $d.Name + ': ' + $d.SideIndicator }Example
$left = @('apple', 'banana', 'cherry')
$right = @('banana', 'cherry', 'date')
$diff = Compare-Object $left $right -IncludeEqual | Sort-Object InputObject
foreach ($d in $diff) { $d.InputObject + ': ' + $d.SideIndicator }
'By name:'
$leftObj = @(
[PSCustomObject]@{Name='apple'; Price=2}
[PSCustomObject]@{Name='pear'; Price=3}
)
$rightObj = @(
[PSCustomObject]@{Name='apple'; Price=2}
[PSCustomObject]@{Name='plum'; Price=4}
)
$diff2 = Compare-Object $leftObj $rightObj -Property Name | Sort-Object Name
foreach ($d in $diff2) { $d.Name + ': ' + $d.SideIndicator }Key points
- Compare-Object: a command that finds differences between two lists.
- The first list is the left list, and the second list is the right list.
- SideIndicator <= means the item is only in the left list.
- SideIndicator => means the item is only in the right list.
- SideIndicator == means the item is in both lists, and it appears only with -IncludeEqual.
- Use -Property with Compare-Object to compare objects by one property.
In this example, the script first compares two word lists with -IncludeEqual and prints each word with its SideIndicator, then compares two object lists by Name and prints each differing name with its SideIndicator.
Note
sort the result by the compared value before printing, so the lines read in order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In Compare-Object output, what does => mean?