Write bytes to a file natively in PowerShell

后端 未结 3 2025
失恋的感觉
失恋的感觉 2020-12-17 09:16

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\"         


        
相关标签:
3条回答
  • 2020-12-17 09:38

    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.

    0 讨论(0)
  • 2020-12-17 09:46

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

    0 讨论(0)
  • 2020-12-17 09:51

    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
    
    0 讨论(0)
提交回复
热议问题