Search code examples
powershellpowershell-2.0

How to get an MD5 checksum in PowerShell


I would like to calculate an MD5 checksum of some content. How do I do this in PowerShell?


Solution

  • 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 solution for older PowerShell offers as identified in the comments (uses a stream, closes it, and supports large files).

    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)))
    

    For older PowerShell version

    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)))