How do I diff two text files in Windows Powershell?

Solution 1:

Figured it out myself. Because Powershell works with .net objects rather than text, you need to use get-content to expose the contents of the text files. So to perform what I was trying to do in the question, use:

compare-object (get-content one.txt) (get-content two.txt)

Solution 2:

A simpler way of doing it is to write:

diff (cat file1) (cat file2)

Solution 3:

Or you could use the DOS fc command like so (This shows the output of both files so you will have to scan for the differences):

fc.exe filea.txt fileb.txt > diff.txt

fc is an alias for the Format-Custom cmdlet so be sure to enter the command as fc.exe. Please note that many DOS utilities don't handle UTF-8 encoding.

You can also spawn a CMD process and run fc within it.

start cmd "/c  ""fc filea.txt fileb.txt >diff.txt"""

This instructs PowerShell to start a process with the 'cmd' program using the parameters in quotes. In the quotes, is the '/c' cmd option to run the command and terminate. The actual command to run by cmd in the process is fc filea.txt fileb.txt redirecting the output to the file diff.txt.

You can use the DOS fc.exe from within powershell.


Solution 4:

diff on *nix is not part of the shell, but a separate application.

Is there any reason you can't just use diff.exe under PowerShell?

You can download a version from the UnxUtils package (http://unxutils.sourceforge.net/)


Solution 5:

compare-object (aka diff alias) is pathetic if you expect it to behave something like a unix diff. I tried the diff (gc file1) (gc file2), and if a line is too long, I can't see the actual diff and more importantly, I can't tell which line number the diff is on.

When I try adding -passthru, I now can see the difference, but I lose which file the difference is in, and I still don't get a line number.

My advice, don't use powershell to find differences in files. As someone else noted, fc works, and works a little better than compare-object, and even better is downloading and using real tools like the unix emulator that Mikeage mentioned.