What is Compare-Object cmdlet do?

The Compare-Object cmdlet compares two sets of objects. One set of objects is the “reference set,” and the other set is the “difference set”. The below format will be out of the comparison.

<= This indicates that property value appears only in the -ReferenceObject set.
=> Indicates that property value appears only in the -differenceObject.
== Indicates that both property value appears the same.

Example:

In the Compare-Object cmdlet, there are two required parameters -referenceObject and -differenceObject. For example, -referenceObject controls the master content, the file which holds all the information, while -differenceObject has the secondary file.

Demo

Let we create two files, the first (Master & Child list) is for reference and the second for comparison. Now we are ready to execute this Compare-Object script.

MasterList.txt

WaterMelon
Grapes
Mango
Oranges
Bananas
Cucumber
Guva

ChildList.txt

Mango
Apple
Oranges
Bananas
Cucumber
WaterMelon
Grapes

Example 1: To Compare Two Files, and List Their Differences

This command compares the contents of two text files. Here Apple is present in the second file (-differenceObject set) not in the first file (-ReferenceObject set)  so the output will be => and Guva is present in the first file and not in the second file, so the output will be <=.

Example 2: To Compare Two Files, with -Parameters

Optional Parameters

-CaseSensitive This indicates that comparisons should be case-sensitive.
-Culture Specifies the culture to use for comparisons.
-Property Specifies an array of properties of the reference and difference objects to compare.
-ExcludeDifferent Indicates that this cmdlet displays only the characteristics of compared objects that are equal
-SyncWindow Specifies the number of adjacent objects that this cmdlet inspects while looking for a match in a collection of objects.
-IncludeEqual Indicates that this cmdlet displays characteristics of compared objects that are equal. By default, only characteristics that differ between the reference and different objects are displayed.
-PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output.

 

NOTE: If the reference set or the difference set is null ($null), Compare-Object generates a terminating error.

 

What do you think?

I hope you have got an idea about how to use PowerShell Compare-Object cmdlet. I would like to have feedback from the readers of my post. Your valuable feedback, question, or comments about this article are always welcome.