Write bytes to a file natively in PowerShell

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.


Powershell Core (v6 and above) no longer have -Encoding byte as an option, so you'll need to use -AsByteStream, e.g:

Set-Content -Path C:\temp\test.jpg -AsByteStream

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.)

Tags:

Powershell