powershell

Write bytes to a file natively in PowerShell


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 "image=@clear.png" 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?


Solution

  • Running C# assemblies is native to PowerShell, therefore you are already writing bytes to a file "natively".

    If you insist, you can use a construction like set-content test.jpg -value (([char[]]$decoded) -join ""), this has a drawback of adding #13#10 to the end of written data. With JPEGs it's bearable, but other files may get corrupt from this alteration. So please stick with byte-optimized routines of .NET instead of searching for "native" approaches - these are already native.