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!

Comments (6)

  1. Anonymous says:

    Nice script, but could you possibly post the reverse?  If you have the hash value, how do you get the string back?

  2. lvovan says:

    This is not possible unless the algorithm you use is a perfect hashing function (i.e. no collision), which is a very particular case scenario. You will generally want to use hashes for passwords or for indexing.


  3. Anonymous1002 says:

    If you want to get the reverse, I believe it is not a hash algorithm but compression algorithm

  4. Guest says:

    Loop it seem to be like this

       $res = ""

       foreach($byte in $hash)


           $res += [System.String]::Format("{0:X2}", $byte)



  5. Tom C says:

    Replacing $res += $byte.ToString() with $res += $byte.ToString("x2") gave me the desired hash value for a MD5 hash

  6. jonp says:



    be ok