Sometimes you want to test if two files are the same. You could generate hashes (MD5, SHA) of the files, but it might take some time to compute them. A byte by byte comparison might be the faster instead. If something is not the same, we can stop the check.

After seeing some code on StackOverflow, I’ve decided to “port” the code to a PowerShell script. It might do some good for all the PS-ers out there.

When both files have the same file size, it makes a byte-by-byte comparison of both files. As soon as one byte differs, the function returns $false. Good enough for the occasional comparison job.

function FilesAreEqual
{
   param([System.IO.FileInfo] $first, [System.IO.FileInfo] $second) 
   $BYTES_TO_READ = 8;

   if ($first.Length -ne $second.Length)
   {
        return $false;
   }

   $iterations = [Math]::Ceiling($first.Length / $BYTES_TO_READ);
   $fs1 = $first.OpenRead();
   $fs2 = $second.OpenRead();

   $one = New-Object byte[] $BYTES_TO_READ;
   $two = New-Object byte[] $BYTES_TO_READ;

   for ($i = 0; $i -lt $iterations; $i = $i + 1)
   {
       $fs1.Read($one, 0, $BYTES_TO_READ) | out-null;
       $fs2.Read($two, 0, $BYTES_TO_READ) | out-null;

       if ([BitConverter]::ToInt64($one, 0) -ne 
           [BitConverter]::ToInt64($two, 0))
       {
           $fs1.Close();
           $fs2.Close();
           return $false;
       }
   }

   $fs1.Close();
   $fs2.Close();

   return $true;
}

You can use it by giving it two files:

FilesAreEqual c:\temp\test.html c:\temp\test.html

Enjoy!