PowerShell: Get MD5 Hashing Signature of a File

# Get-MD5-Hash.ps1

# Get-FileHash (PowerShell 4.0+) replacement for Windows 2008. Forward-compatible.
function getMd5{
param(
$file,
$md5 = (New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider)
)

# $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($file))); # This line has the issue of 2GB file size limit
try{
$stream = [System.IO.File]::Open("$file",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read);
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream));
$stream.Dispose();
$stream.Close();
return $hash;
}
catch{
return $null;
}
}

# This is an alternative method, utilizing certutil.exe being bundled into the Windows OS for purposes of SSL encryption/decryption
function getHash{
param(
$file = "C:\temp\somefile.txt"
)
$hash=(certutil -hashfile $file)[1]; #'certutil -hashfile $file MD5' command doesn't work on Windows 2008
return $hash
}

$file="D:\somefile.exe"
getMd5 -file $file

Leave a Reply

Your email address will not be published. Required fields are marked *