5/30/09

PowerShell Hash Scripts for File Comparisons

See the Windows PowerShell Cookbook recipe 17.10 "Get the MD5 or SHA1 Hash of a File", for original script.

GetFileHash returns the hash value for a file. The hash type can be any hash class from the System.Security.Cryptography namespace, e.g. MD5, SHA1, SHA256, SHA512.
CompareFileHash returns true if the files have the same hash.
CompareFileHashInfo returns the hash comparison information.
GetFileHashObject returns a file hash wrapper object.
function getFileHash($file, $hashType)
{
$stream = new-object io.streamReader $file
$hash = $hashType::create().computeHash($stream.baseStream)
$stream.close()
trap
{
if ($stream -ne $null)
{
$stream.close()
}
break
}
[string] $hash
}

function compareFileHash($file1, $file2, $hashType)
{
(getFileHash $file1 $hashType) -eq (getFileHash $file2 $hashType)
}

function compareFileHashInfo($file1, $file2, $hashType)
{
$f1 = getFileHashObject $file1 $hashType
$f2 = getFileHashObject $file2 $hashType

$f1
$f2
"Hash Type: " + $hashType.name
"Duplicate Files: " + ($f1.hash -eq $f2.hash)
}

function getFileHashObject($file, $hashType)
{
$fileHash = new-object psObject
$fileHash | add-member noteProperty file $file
$fileHash | add-Member noteProperty hash (getFileHash $file $hashType)
return $fileHash
}

Examples
>> $hashType = [system.security.cryptography.MD5]
>> getFileHash c:\file1.txt $hashType
52 85 168 127 81 223 163 157 187 191 244 34 221 99 48 201

>> compareFileHash c:\file1.txt c:\file2.txt $hashType
False

>> compareFileHashInfo c:\file1.txt c:\file2.txt $hashType | fl
file : c:\file1.txt
hash : 52 85 168 127 81 223 163 157 187 191 244 34 221 99 48 201

file : c:\file2.txt
hash : 100 221 101 253 63 62 26 193 155 80 181 198 78 247 255 196

Hash Type: MD5
Duplicate Files: False