Tricking PowerShell Into Treating a String as a Stream

The PowerShell cmdlet Get-FileHash accepts only files or streams as inputs. If I want to generate a hash for a string, I could save it as a file and then feed that file to the command, or I could simply send the string to the command as a string:

PS C:\Working> $stringStream = [System.IO.MemoryStream]::new()
PS C:\Working> $writer = [System.IO.StreamWriter]::new($stringStream)
PS C:\Working> $writer.write("Please hash me.")
PS C:\Working> $writer.Flush()
PS C:\Working> $stringStream.Position = 0
PS C:\Working> Get-FileHash -InputStream $stringStream | Select-Object Hash

Hash
----
50981297AEA627CA3AA5026EB31475FAFD0D28D430165506A2A69B7A30C36AC6

Leave a Reply