在 PowerShell 中以本机方式将字节写入文件 [英] Write bytes to a file natively in PowerShell
问题描述
我有一个脚本,用于测试返回 base64 编码图像的 API.我目前的解决方案是这样的.
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
这可行,但我希望能够在 PowerShell 中以本机方式编写字节数组,而无需从 [io.file] 获取源.
This works, but I would like to be able to write the byte array natively in PowerShell, without having to source from [io.file].
我在 PowerShell 中写入 $decoded 的尝试都导致写入 整数 字节值的字符串编码列表.(例如)
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?
推荐答案
运行 C# 程序集是 PowerShell 的本机,因此您已经本机"将字节写入文件.
Running C# assemblies is native to PowerShell, therefore you are already writing bytes to a file "natively".
如果你坚持,你可以使用像 set-content test.jpg -value (([char[]]$decoded) -join "")
这样的结构,这有一个缺点#13#10 到写入数据结束.对于 JPEG,这是可以忍受的,但其他文件可能会因这种更改而损坏.因此,请坚持使用 .NET 的字节优化例程,而不是搜索本机"方法 - 这些方法已经是本机了.
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 中以本机方式将字节写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!