I have a script for testing an API which returns a base64 encoded image. My current solution is this.
$e = (curl.exe -H "Content-Type: multipart/form-data" -F "[email protected]" localhost:5000) $decoded = [System.Convert]::FromBase64CharArray($e, 0, $e.Length) [io.file]::WriteAllBytes('out.png', $decoded) # <--- line in question Get-Content('out.png') | Format-Hex
This works, but I would like to be able to write the byte array natively in PowerShell, without having to source from [io.file].
My attempts of writing $decoded in PowerShell all resulted in writing a string-encoded list of the integer byte values. (e.g.)
42 125 230 12 34 ...
How do you do this properly?
[IO. File]::WriteAllBytes() is the correct way of writing bytes to a file in PowerShell.
All variables in PowerShell are .NET objects, including 8-bit unsigned integer bytes. A byte object is an object of type System.Byte in the .NET class library, hence, it has properties and methods accessible to PowerShell (you can pipe them into get-member).
The Value parameter includes the text string to append to the file. The Force parameter writes the text to the read-only file. The Get-Content cmdlet uses the Path parameter to display the file's contents.
The Set-Content cmdlet lets you write raw bytes to a file by using the Byte
encoding:
$decoded = [System.Convert]::FromBase64CharArray($e, 0, $e.Length) Set-Content out.png -Value $decoded -Encoding Byte
(However, BACON points out in a comment that Set-Content is slow: in a test, it took 10 seconds, and 360 MB of RAM, to write 10 MB of data. So, I recommend not using Set-Content if that's too slow for your application.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With