Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PowerShell to quickly test whether the content of two files is identical

Tags:

powershell

As part of a larger PowerShell script, I want to test whether the contents of two binary files are identical.

I think the following is logically correct:

if (@(Compare-Object 
    $(Get-Content f1.txt -encoding byte) 
    $(Get-Content f2.txt -encoding byte) 
    -sync 0).length -eq 0) {
    "same" 
} else {
    "different"
}

However, the above runs very slowly as it's really using Compare-Object for something that is begging for a much simpler implementation.

I'm looking for something that gives the same logical result, but uses some faster low level file comparison.

I do not need or want any description of the differences, or any text output, just a logical test that gives me a boolean result.

like image 451
John Rees Avatar asked Oct 17 '11 00:10

John Rees


People also ask

How do I compare the contents of two files in PowerShell?

To compare the files, use the compare-object cmdlet. From Microsoft: The Compare-Object cmdlet compares two sets of objects. One set of objects is the “reference set,” and the other set is the “difference set.”

How can I tell if two files have the same content?

Comparison Using cmp GNU cmp compares two files byte by byte and prints the location of the first difference. We can pass the -s flag to find out if the files have the same content. Since the contents of file1 and file2 are different, cmp exited with status 1.

How can you compare the contents of two different files?

Use the diff command to compare text files. It can compare single files or the contents of directories. When the diff command is run on regular files, and when it compares text files in different directories, the diff command tells which lines must be changed in the files so that they match.

What PowerShell command is used to compare the difference between the content of two or more?

The Compare-Object cmdlet compares two sets of objects. One set of objects is the reference, and the other set of objects is the difference.


2 Answers

If the files are large, causing compare-object to take much time, you can generate SHA1 hash and compare it.

Or you can read the files byte-by-byte in a loop, breaking at the first non-equal bytes.

like image 98
manojlds Avatar answered Sep 18 '22 01:09

manojlds


if ($(Get-FileHash $fileA).Hash -ne $(Get-FileHash $fileB).Hash) {
  Write-Output "Files $fileA and $fileB aren't equal"
}
like image 44
Rusted Avatar answered Sep 20 '22 01:09

Rusted