PowerShell File Comparison

A very common task is to compare two files for differences. We may perform this task as part of a post install verification process. PowerShell provides a couple of Cmdlets that aid with this activity. Consider the below two files that we wish to compare. Below is a file named 1.txt.

1
2
3
This is line 1
This is line 2
This is line 3

Below the file 2.txt contents are in reverse order and is missing the line “This is line 2”.

1
2
This is line 3
This is line 1

We can compare these two files using the Compare-Object cmdlet.

1
2
3
$content1 = Get-Content .\1.txt
$content2 = Get-Content .\2.txt
Compare-Object Get-Content .\1.txt Get-Content .\2.txt

Above we copy the contents of the files into variables $content1 and $content2. We then use the Compare-Object cmdlet to compare the files.

1
2
3
InputObject                             SideIndicator                          
-----------                             -------------                          
This is line 2                          <=

Conclusion

In this small tutorial we looked at how we can use PowerShell to compare files.