Search code examples
powershellpowershell-7.0

How do I pipe a byte stream through external executables?


Using Get-Content -AsByteStream, one can read file as a byte stream.

Using Set-Content -AsByteStream, one can create a file from a byte stream.

However, I haven't found a way to pass these byte streams to other non-PowerShell commands. Pipes between external commands always decode the data as strings, which mangles binary. (ex. cmd /c type a.zip > b.zip produces a corrupt file in PowerShell while cmd /c "type a.zip > b.zip" results in an identical file)

cmd /c --% or Start-Process -RedirectStandardInput do solve part of the problem, but it can get a bit tedious if any of the involved commands is another cmdlet. Is there a PowerShell-native way to handle executable input/output as a stream of byte?


Solution

  • There is an open closed issue on GitHub for that. The thread offers a variety of workarounds. (found via this answer)

    Edit: There is a PowerShell Module to wrap native commands by @GeeLaw though I haven't tried.

    Edit^2(2023-06-29): @SeeminglyScience implemented awesome PSNativeCommandPreserveBytePipe experimental feature and it's incorporated as part of v7.4.0-preview.4. It can be enabled with Enable-ExperimentalFeature PSNativeCommandPreserveBytePipe.

    Edit^3(2023-11-16): PowerShell 7.4 has been released. The feature has become built-in, so cmd /c type a.zip > b.zip now produces an identical file without any configuration. I guess it's still difficult to pass bytestreams between cmdlets, but this solves most of the case for me.