Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write bytes to a file natively in PowerShell

Tags:

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 "[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?

like image 290
Kaelan Fouwels Avatar asked Aug 06 '15 12:08

Kaelan Fouwels


People also ask

How do you write bytes in PowerShell?

[IO. File]::WriteAllBytes() is the correct way of writing bytes to a file in PowerShell.

What is byte 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).

What parameter can be specified when using SET content in order to write data to a read only file?

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.


1 Answers

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

like image 138
Tanner Swett Avatar answered Sep 22 '22 06:09

Tanner Swett