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.
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.”
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.
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.
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.
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.
if ($(Get-FileHash $fileA).Hash -ne $(Get-FileHash $fileB).Hash) {
Write-Output "Files $fileA and $fileB aren't equal"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With