Generating MD5 Hashes from Text

by Oct 26, 2017

The Get-FileHash cmdlet can generate hash codes for file content. It cannot generate hash codes for arbitrary text, though. And it is available only in PowerShell 5 and better.

So here is a small function that uses the .NET Framework to generate MD5 hashes from any text:

Function Get-StringHash 
{ 
    param
    (
        [String] $String,
        $HashName = "MD5"
    )
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($String)
    $algorithm = [System.Security.Cryptography.HashAlgorithm]::Create('MD5')
    $StringBuilder = New-Object System.Text.StringBuilder 
  
    $algorithm.ComputeHash($bytes) | 
    ForEach-Object { 
        $null = $StringBuilder.Append($_.ToString("x2")) 
    } 
  
    $StringBuilder.ToString() 
}

Each text results in a unique (and small) hash code, so it can be used to quickly determine whether texts are identical. It can also be used to check whether large texts have changed.

 
PS C:\> Get-StringHash "Hello World!" 
ed076287532e86365e841e92bfc50d8c

PS C:\> 
 

Twitter This Tip! ReTweet this Tip!