Hashing Text

by Jun 22, 2021

PowerShell comes with Get-FileHash which reads a file and calculates a unique hash value. That’s great to test whether files have identical content. However, there is no way to hash plain texts.

Of course, you could write the text you want to hash to a file, then use Get-FileHash.

A better way is a largely unknown feature of Get-FileHash. Instead of submitting a path to a file, you can also submit a so called “MemoryStream”, and when you load the memory stream with the text of your choice, you get back the hash:

$text = 'this is a test'

$memoryStream = [System.IO.MemoryStream]::new()
$streamWriter = [System.IO.StreamWriter]::new($MemoryStream)
$streamWriter.Write($text)
$streamWriter.Flush()
$memoryStream.Position = 0
$hash = Get-FileHash -InputStream $MemoryStream -Algorithm 'SHA1' 
$memoryStream.Dispose()
$streamWriter.Dispose()
$hash.Hash

Just don’t forget to dispose the MemoryStream and StreamWriter objects after use to free memory.


Twitter This Tip! ReTweet this Tip!