November 18th, 2013

PowerTip: Compare the Contents of Files with PowerShell

Doctor Scripto
Scripter

Summary: Learn how to use Windows PowerShell to compare the contents of two file.

Hey, Scripting Guy! Question How can I use Windows PowerShell to compare the contents of two files?

Hey, Scripting Guy! Answer 

  • If the files are text files, use Compare-Object:

Compare-Object -ReferenceObject (Get-Content .diskcapacity.csv) -DifferenceObject
(Get-Content .diskcapacity2.csv)

Note  You have to get the content of the two files and perform the comparison on the two resultant objects. If you use only the file names, you will get a comparison of the file objects rather than the content.

  • If there are no differences between the contents of the two files, you won’t see any output. Test what is happening by using the –IncludeEqual parameter:

Compare-Object -ReferenceObject (Get-Content .diskcapacity.csv) -DifferenceObject
(Get-Content .diskcapacity2.csv) -IncludeEqual

This outputs each line that matches with an equality indicator. You will get a lot of output if the files are large! 

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.