How to get an MD5 checksum in PowerShell How to get an MD5 checksum in PowerShell powershell powershell

How to get an MD5 checksum in PowerShell


If the content is a string:

$someString = "Hello, World!"$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider$utf8 = New-Object -TypeName System.Text.UTF8Encoding$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))

If the content is a file:

$someFilePath = "C:\foo.txt"$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))

Starting in PowerShell version 4, this is easy to do for files out of the box with the Get-FileHash cmdlet:

Get-FileHash <filepath> -Algorithm MD5

This is certainly preferable since it avoids the problems the first solution offers as identified in the comments (uses a stream, closes it, and supports large files).


If you are using the PowerShell Community Extensions there is a Get-Hash commandlet that will do this easily:

C:\PS> "hello world" | Get-Hash -Algorithm MD5Algorithm: MD5Path       :HashString : E42B054623B3799CB71F0883900F2764


Here's a function I use that handles relative and absolute paths:

function md5hash($path){    $fullPath = Resolve-Path $path    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider    $file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)    try {        [System.BitConverter]::ToString($md5.ComputeHash($file))    } finally {        $file.Dispose()    }}

Thanks to @davor above for the suggestion to use Open() instead of ReadAllBytes() and to @jpmc26 for the suggestion to use a finally block.