在PowerShell中将字节本地写入文件

Kae*_*els 18 powershell

我有一个用于测试API的脚本,它返回base64编码的图像.我目前的解决方案是这样.

$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
Run Code Online (Sandbox Code Playgroud)

这有效,但我希望能够在PowerShell中本地编写字节数组,而不必从[io.file]中获取.

在PowerShell中编写$ decode的尝试都导致编写了一个整数字节值的字符串编码列表.(例如)

42
125
230
12
34
...
Run Code Online (Sandbox Code Playgroud)

你怎么做得好?

Tan*_*ett 30

Set-Content cmdlet(现在?)允许您使用Byte编码将原始字节写入文件:

$decoded = [System.Convert]::FromBase64CharArray($e, 0, $e.Length)
$decoded | Set-Content out.png -Encoding Byte
Run Code Online (Sandbox Code Playgroud)

  • @TannerSwett,“-Encoding Byte”被[替换](https://www.jonathanmedd.net/2017/12/powershell-core-does-not-have-encoding-byte-replaced-with-new-parameter-asbytestream .html)在 PowerShell 中使用 `-AsByteStream` ≥[6](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/set-content?view=powershell-6)。 (4认同)
  • @jimhark考虑到这一点,似乎这个答案应该包括(如果不推荐)将其写为“Set-Content out.png -Value $decoded -Encoding Byte”。使用“Measure-Command”和任务管理器对 10 MB 数组的两次调用进行快速基准测试,为“$byteArray | 提供 3 分钟/+5.5 GB RAM” PS5.1 中“Set-Content ... -Encoding Byte” 与 10 秒/+360 MB RAM 的“Set-Content ... -Value $byteArray -Encoding Byte”;一个很大的进步,但仍然很糟糕。在 PS7 上使用“-AsByteStream”可使管道速度加快 45 秒,但与“-Value”_没有区别_。如果可能的话,我会说避免“Set-Content”。 (3认同)
  • 惯用的(高级的)解决方案。 (2认同)
  • 为什么这么慢?写入14兆字节需要2分多钟。 (2认同)

Mar*_*son 17

Powershell Core(v6 及更高版本)不再有-Encoding byte选项,因此您需要使用-AsByteStream,例如:

Set-Content -Path C:\temp\test.jpg -AsByteStream
Run Code Online (Sandbox Code Playgroud)

  • - 缺少值参数。正确的命令是:`Set-Content -Path 'out.png' -Value $decoded -AsByteStream;` (3认同)

Ves*_*per 11

运行C#程序集是PowerShell的原生程序,因此您已经在"本机"中将字节写入文件.

如果你坚持,你可以使用类似的结构set-content test.jpg -value (([char[]]$decoded) -join ""),这有一个缺点,即在写入数据的末尾添加#13#10.使用JPEG,它是可以忍受的,但其他文件可能会因此更改而损坏.因此,请坚持使用.NET的字节优化例程,而不是搜索"本机"方法 - 这些已经是原生的.