Write bytes to a file natively in PowerShell

2020-04-02 01:51发布

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?

标签: powershell
2条回答
爷、活的狠高调
2楼-- · 2020-04-02 02:24

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.

查看更多
家丑人穷心不美
3楼-- · 2020-04-02 02:45

The Set-Content cmdlet (now?) lets you write raw bytes to a file by using the Byte encoding:

$decoded = [System.Convert]::FromBase64CharArray($e, 0, $e.Length)
$decoded | Set-Content out.png -Encoding Byte
查看更多
登录 后发表回答