Compare two sets of objects e.g. compare the content within two files.
Syntax
Compare-Object [-referenceObject] PSObject[] [-differenceObject] PSObject[]
[-syncWindow int] [-property Object[]] [-caseSensitive]
[-culture string] [-excludeDifferent] [-includeEqual]
[-passThru] [CommonParameters]
Key
-referenceObject PSObject[]
Object(s) used as a reference for comparison.
-differenceObject PSObject[]
Object(s) to compare to the reference object(s).
-syncWindow int
Defines a search region where an attempt is made to re-sync the order if there is no match.
-property Object[]
Properties of the objects to compare.
-caseSensitive
Make comparisons case-sensitive.
-culture string
The culture to use for comparisons.
-excludeDifferent
Display only the characteristics of compared objects that are equal.
-includeEqual
Displays characteristics of compared objects that are equal.
By default only differences are displayed.
-passThru
Pass the object created by this cmdlet through the pipeline.
CommonParameters
common parameters: -Verbose, -Debug, -ErrorAction, -ErrorVariable, -OutVariable.
Compare-Object compares two sets of objects, one the 'reference' set and the 'difference' set.
The results indicate a property value appears only in the Reference set (indicated by <= ), only in the Difference set (indicated by => ) or in both objects (indicated by == when -IncludeEqual parameter is specified.)
Examples
Compare the content of two text files:
PS C:\>compare-object -referenceobject $(get-content C:\file1.txt) $(get-content C:\file2.txt)
Compare the processes running before and after starting a copy of notepad.exe, using Get-Process to retrieve the processes running and store them in a variable:
PS C:\>$proc_before = get-process notepad $proc_after = get-process compare-object -referenceobject $proc_before -differenceobject $proc_after
"With the greater part of rich people, the chief enjoyment of riches consists in the parade of riches" - Adam Smith
Related:
ForEach-object - Loop for each object in the pipeline
group-object - Group the objects that contain the same value for a common property
measure-object - Measure aspects of object properties and create objects from those values
new-object - Create a new .Net object
select-object - Select objects based on parameters set in the Cmdlet command string
sort-object - Sort the input objects by property value
tee-object - Send input objects to two places
where-object - Filter input from the pipeline allowing operation on only certain objects
Equivalent bash commands: diff3 - Show differences among three files