PowerShell : Getting the hash value for a string

A simple yet often useful scripting task is getting the hash value for a string. Since I recently wrote this very short function for my colleague Laurent Banon (blog) allow me to share it with you.

function Hash($textToHash)

{

    $hasher = new-object System.Security.Cryptography.SHA256Managed

    $toHash = [System.Text.Encoding]::UTF8.GetBytes($textToHash)

    $hashByteArray = $hasher.ComputeHash($toHash)

    foreach($byte in $hashByteArray)

    {

         $res += $byte.ToString()

    }

    return $res;

}

And its usage :

PS #> . Hash.ps1

PS #> Hash("hi")

Instead of SHA256, you can use other hashing algorithms like the ones available by default in .NET 3.5 ou 4 :

Happy scripting!