Sunday, June 11, 2017

Storing files inside PowerShell scripts

I recently wrote a Super User answer where I needed to stash an image in a PowerShell script and manipulate it a bit. The easiest way of storing a lot of non-text data is to encode it in Base64.

[Convert]::ToBase64String((gc .\myfile.bin -Encoding Byte))

Pipe that into scb to copy it to your clipboard. Then paste that into a string variable in your script. At runtime, that can be decoded back into the raw bytes.

$bin = [Convert]::FromBase64String($b64)

To open the byte array as a stream (suitable for many .NET APIs), create a MemoryStream. I used the constructor overload with an extra parameter because otherwise PowerShell will think each byte in the array should be its own parameter.

$ms = New-Object System.IO.MemoryStream $bin, $false

Then you can, for example, load that stream as an image.

No comments:

Post a Comment