PowerShell: Use Compare-Object and Only Show Differences


You can use the Compare-Object cmdlet to compare two sets of objects in PowerShell.

By default, the Compare-Object cmdlet displays the values that are different between the two objects along with a SideIndicator to indicate which object a given value belongs to.

To output only the different values between two objects, you can use the following syntax:

Compare-Object $object1 $object2 | Select -ExpandProperty InputObject

This particular example will return only the values that are different between $object1 and $object2.

The following example shows how to use this syntax in practice.

Example: How to Use Compare-Object and Only Show Differences

Suppose we create two arrays in PowerShell named $array1 and $array2 and we would like to compare the the differences between the two arrays.

Suppose we use the Compare-Object cmdlet to do so:

$array1 = @(1,2,3,4,5,6,7,8,9,10)
$array2 = @(6,7,8,9,10,11,12,13)

Compare-Object $array1 $array2

The following screenshot shows how to use this syntax in practice:

The InputObject column displays values that only occur in one of the arrays while the SideIndicator column shows which array the value belongs to.

For example, we can see:

  • The value 11 only occurs in the second array ( => )
  • The value 12 only occurs in the second array ( => )
  • The value 13 only occurs in the second array ( => )
  • The value 1 only occurs in the first array ( <= )
  • The value 2 only occurs in the first array ( <= )

And so on.

To only display the values that are different between the two arrays, we can use the following syntax:

$array1 = @(1,2,3,4,5,6,7,8,9,10)
$array2 = @(6,7,8,9,10,11,12,13)

Compare-Object $array1 $array2 | Select -ExpandProperty InputObject

The following screenshot shows how to use this syntax in practice:

PowerShell Compare-Object only show differences

Notice that this only returns the values that are different between the two objects.

By using the -ExpandProperty operator we were able to specify that we only wanted to return the InputObject column from the output.

Note: You can find the complete documentation for the Compare-Object cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

How to Compare Two Arrays in PowerShell
How to Compare Two Strings in PowerShell
How to Compare Two Files in PowerShell
How to Compare Two Folders in PowerShell

Leave a Reply