Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a stream object in Powershell?

Tags:

powershell

I want to make a string fit for consumption as a stream by e.g. Get-FileHash command using its -InputStream argument.

The reason I want this is that I need to digest a string, and not contents of a file. I do not want to temporarily store said string in a file just to digest it.

I know this can be done using half a dozen .NET object and methods, something that is trivially supported by Powershell, but I am just curious whether there is an existing PS command that turns a string object into a stream so I can do something like the following (assuming Convert is what gets you a stream from a string):

Get-FileHash -InputStream (Convert "Quick brown fox jumps over the lazy dog.") -Algorithm SHA512
like image 569
amn Avatar asked Jan 18 '18 13:01

amn


2 Answers

You can use some .NET functions:

$stream = [IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes("Quick brown fox jumps over the lazy dog."))
Get-FileHash -InputStream $stream -Algorithm SHA512
like image 187
Paweł Dyl Avatar answered Oct 13 '22 22:10

Paweł Dyl


There is a script in the Microsoft Script Gallery that does exactly what you ultimately want to do - that is, it takes a string and returns the hash for the string. See Get-StringHash in the Technet Powershell Script Gallery.

like image 33
Jeff Zeitlin Avatar answered Oct 13 '22 21:10

Jeff Zeitlin