The following blog will cover methods to compare objects in PowerShell.
How to Compare Objects With PowerShell Using the “Compare-Object” Cmdlet?
The cmdlet “Compare-Object” in PowerShell compares the objects from the two corresponding files, folders, or arrays. It takes two parameters, “-ReferenceObject” and “-DifferenceObject”. The former parameter references the file, and the latter parameter differentiates the objects from a file.
These are the indicators that are displayed after the comparison of the objects:
Indicator | Description |
---|---|
== | Confirms that the content is present in both files. |
=> | Confirms that content is present only in the “-DifferenceObject” file. |
<= | Confirms that content is present only in the “-ReferenceObject” file. |
Example 1: Compare the Objects Within a File
This example will compare the objects within a file using the “Compare-Object” cmdlet:
$Dif_File = Get-Content C:\\Doc\\File.txt
Compare-Object -ReferenceObject $Ref_file -DifferenceObject $Dif_File -IncludeEqual
According to the above code:
- First, initialize the two variables “$Ref_File” and “$Dif_File”.
- Assign each of them the “Get-Content” cmdlet to retrieve the data within the given files and specify the path of the two text files.
- Lastly, to compare the files, first, invoke the “Compare-Object” cmdlet, then add the “-ReferenceObject”, and assign the reference file assigned variable, which is “$Ref-File”.
- After that, add another parameter, “-DifferenceObject”, and assign the difference file assigned variable “$Dif-File”.
- At the end, add the “-IncludeEqual” flag to display the matching objects from the referenced file:
Example 2: Compare Files in the Folders
This example will compare the file within two folders using PowerShell “Compare-Object” command:
$Dif_Fold = Get-ChildItem C:\\Doc\\Folder_2\\
Compare-Object $Ref_Fold $Dif_Fold -IncludeEqual
In the above code, the “Get-ChildItem” cmdlet is utilized to retrieve the files from specified folder locations:
Example 3: Compare Two Arrays Using the “Compare-Object” cmdlet
This example will compare objects of two arrays:
$array_2 = @("Dog", "Hen", "Horse")
Compare-Object $array_1 $array_2 -IncludeEqual
According to the above code:
- First, initialize two variables and assign both of the arrays with objects.
- After that, compare both using the “Compare-Object” cmdlet:
Now, evaluate the difference using the description of the side indicators.
Conclusion
The objects in PowerShell are compared using the “Compare-Object” cmdlet. This cmdlet uses the parameters “-ReferenceObject” and “-DifferenceObject”. The former parameter references the file, and the latter parameter differentiates the objects from a file. This write-up has elaborated on the methods to compare files in PowerShell.