powershellhexdump

Converting hexdump command to Format-Hex


I'm currently having trouble with converting the following command:

echo -ne '\x08\x80\01' | hexdump -C

As of right now, I had a command that worked for the majority of the case (e.g. \x08\x7F works). It looks like this:

$bytes = [byte[]]@(0x08, 0x80, 0x01)
$stdout = [Console]::OutputEncoding.GetString($bytes)
Format-Hex -InputObject $stdout

I simplified the command above. There would be no point of doing the encoding since we could just execute [byte[]]@(0x08, 0x80, 0x01) | Format-Hex. The encoding is done by Powershell here, it comes from the execution of an external command (protoc).

hexdump outputs:

08 80 01

Format-Hex outputs:

08 EF BF BD 01

I assume this is an encoding problem but I can't figure out how to solve it.


Solution

  • According to your edit history, you want to pipe bytes from a native command to a PowerShell cmdlet (native | ps). Currently, this is not possible1. But you can use a temporary file as a workaround:

    # Create a temporary file
    $TempFile = New-TemporaryFile
    
    # Write the bytes into the temporary file
    Start-Process protoc -ArgumentList "--encode=Encoding ./encoding.proto" -RedirectStandardOutput $TempFile -Wait
    
    # Print a hexdump of the bytes
    Format-Hex -Path $TempFile
    
    # (Optional) Remove the temporary file
    Remove-Item $TempFile
    

    FYI, with PowerShell 7.4, you are able to pipe bytes from a native command to another native command (native | native).


    1 From about_Pipelines:

    PowerShell allows you to include native external commands in the pipeline. However, it's important to note that PowerShell's pipeline is object-oriented and doesn't support raw byte data.

    Piping or redirecting output from a native program that outputs raw byte data converts the output to .NET strings. This conversion can cause corruption of the raw data output.