johnnycrash
johnnycrash

Reputation: 5344

Output binary data on PowerShell pipeline

I need to pipe some data to a program's stdin:

  1. First 4 bytes are a 32-bit unsigned int representing the length of the data. These 4 bytes are exactly the same as C would store an unsigned int in memory. I refer to this as binary data.
  2. Remaining bytes are the data.

In C, this is trivial:

WriteFile(h, &cb, 4);  // cb is a 4 byte integer
WriteFile(h, pData, cb);

or

fwrite(&cb, sizeof(cb), 1, pFile);
fwrite(pData, cb, 1, pFile);

or in C# you would use a BinaryWriter (I think this code is right, i don't have C# lying around right now...)

Bw.Write((int)Data.Length);
Bw.Write(Data, 0, Data.Length);

In PowerShell I'm sure it's possible, but this is as close as I could get. This is obviously printing out the 4 bytes of the size as 4 human readable numbers:

$file = "c:\test.txt"
Set-content $file "test data" -encoding ascii
[int]$size = (Get-ChildItem $file).Length
$bytes = [System.BitConverter]::GetBytes($size)
$data = Get-content $file
$bytes
$data
11
0
0
0
test data

I need the binary data sent out on the pipe to look like this (\xA is the escaped representation of a non printable character, I don't want '\' in my output, I want the BYTE that '\xA' represents in the output) :

\xA\x0\x0\0test data

I don't know how to write a byte array out the pipeline in binary format. I also don't know how to get rid of the carriage returns.

EDIT: I have found that I can do this:

$file = "c:\test.txt"
Set-content $file "test data" -encoding ascii
"File: ""{0}""" -f (Get-content $file)
[int]$size = (Get-ChildItem $file).Length
"Size: " + $size
$bytes = [System.BitConverter]::GetBytes($size)
"Bytes: " + $bytes
$data = Get-content $file
$file1 = "c:\test1.txt"
Set-content $file1 $bytes -encoding byte
Add-Content $file1 $data -encoding ASCII
"File: ""{0}""" -f (Get-content $file1)
"Size: " + (Get-ChildItem $file1).Length
File: "test data"
Size: 11
Bytes: 11 0 0 0
File: "   test data"
Size: 15

But this requires me to build a temporary file. There must be a better way!

EDIT: That solution above, corrupts any character code > 127. There is no "binary" encoding mode for the pipe.

EDIT: I finally discovered a roundabout way to get a BinaryWriter wired up to an application's stdin. See my answer.

Upvotes: 23

Views: 23043

Answers (6)

R. Wang
R. Wang

Reputation: 353

I happened to face a very similar issue (was trying to use built-in Powershell as part of Native messaging with browser extension), and the messaging between browser and native application was serialized using JSON, UTF-8 encoded and is preceded with an unsigned 32-bit value containing the message length in native byte order.

Obviously Powershell Read-Host doesn't work as the message has no line break, nor does ([System.Diagnostics.Process]::GetCurrentProcess()).StandardInput which happens to be $null. Write-Output won't allow binary data either. [System.Console]::In and [System.Console]::Out are non-blocking but at least it works, so this is what I did...


#ISO-8859-1 is byte-preserving encoding and would be used to write raw bytes
$iso = [System.Text.Encoding]::GetEncoding('ISO-8859-1') 
$utf8 = [System.Text.UTF8Encoding]::new($false) #No UTF-8 BOM
$in = [System.Console]::In
$out = [System.Console]::Out
[System.Console]::InputEncoding = $iso
While ($read -lt 4) {
    Try {
        $len = [char[]] @(0,0,0,0)
        $read = 0
# Keep reading until 4 bytes are read 
        While ($true) { 
            $read = $read + $in.Read($len, $read, 4 - $read);
        }
        $len = $iso.GetBytes($len);
        $len = [System.BitConverter]::ToUInt32($len, 0)
        "  Length: $len" >> out.log
        $read = 0
        $bytes = [char[]]::new($len)
#Read $len number of bytes
        While ($read -lt $len) { 
            $read = $read + $in.Read($bytes, $read, $len - $read);
        }
        $str = $utf8.GetString($bytes, 0, $len)
        $str >> out.log
        $res = 'Some kind of response string goes here'
#First, write 4 bytes corresponding to length of message, then UTF-8 encoded message itself
        [System.Console]::OutputEncoding = $iso
        $out.Write($iso.GetString([System.BitConverter]::GetBytes([int]$res.Length)))
        [System.Console]::OutputEncoding = $utf8
        $out.Write($res)

    } Catch {
        $Error[0]>>out.log
    }
}

Moral of the story: working with binary data in Powershell is very hard...

Upvotes: 0

johnnycrash
johnnycrash

Reputation: 5344

Bill_Stewart is correct that you can't pipe binary data. When you use the | operator, PowerShell uses the encoding dictated by $OutputEncoding. I could not find an encoding that would not corrupt data.

I found something that does work though, BinaryWriter.

Here is my test code, starting with C:\foo.exe that simply outputs the data it receives:

#include <windows.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); 
    BYTE aBuf[0x100];
    int nRet;
    DWORD cbRead;
    if (!(nRet = ReadFile(hInput, aBuf, 256, &cbRead, NULL)))
        return printf("err: %u %d %d", cbRead, nRet, GetLastError());
    for (int i=0 ; i<256 ; ++i)
        printf("%d ", aBuf[i]);
    return 0;
}

This PowerShell script demonstrates the "corruption":

$data = [Byte[]] (0..255)

$prefix = ($data | ForEach-Object {
  $_ -as [Char]
}) -join ""
"{0}" -f $prefix
$OutputEncoding = [System.Text.Encoding]::GetEncoding("us-ascii")
$prefix | c:\foo.exe

Here is the output. First you see that $prefix does have the complete charset. Second, you see the data that got to foo.exe has been converted.

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 5
0 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 9
7 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 63 63 63 63 63 63 63 
63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 
63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 
63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63

Using BinaryWriter works:

$data = [Byte[]] (0..255)

$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo 
$ProcessInfo.FileName = "C:\foo.exe"
$ProcessInfo.RedirectStandardInput = $true 
$ProcessInfo.RedirectStandardOutput = $true 
$ProcessInfo.UseShellExecute = $false 
$Proc = New-Object System.Diagnostics.Process 
$Proc.StartInfo = $ProcessInfo 
$Proc.Start() | Out-Null 

$Writer = New-Object System.IO.BinaryWriter($proc.StandardInput.BaseStream);
$Writer.Write($data, 0, $data.length)
$Writer.Flush()
$Writer.Close()

$Proc.WaitForExit()
$Proc.StandardOutput.ReadToEnd()
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 5
0 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 9
7 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 1
33 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 16
8 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

So, my final script which writes the length in binary before writing the data file, would look something like this:

$data = [Byte[]] (0..255)

$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo 
$ProcessInfo.FileName = "C:\foo.exe"
$ProcessInfo.RedirectStandardInput = $true 
$ProcessInfo.RedirectStandardOutput = $true 
$ProcessInfo.UseShellExecute = $false 
$Proc = New-Object System.Diagnostics.Process 
$Proc.StartInfo = $ProcessInfo 
$Proc.Start() | Out-Null 

$Writer = New-Object System.IO.BinaryWriter($proc.StandardInput.BaseStream);
$Writer.Write([Int32]$data.length)
$Writer.Write($data, 0, $data.length)
$Writer.Flush()
$Writer.Close()

$Proc.WaitForExit()
$Proc.StandardOutput.ReadToEnd()

You can see the first 4 bytes 0 1 0 0 are the raw binary representation of an [Int32] that is equal to 256:

0 1 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 1
31 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 16
6 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

Upvotes: 18

Carsten
Carsten

Reputation: 2191

Shorter sample using a binaryWriter:

$file = 'c:\temp\test.txt'
$test = [byte[]](0..255)
$mode = [System.IO.FileMode]::Create
$stream = [System.IO.File]::Open($file, $mode)
$bw = [System.IO.BinaryWriter]::new($stream)
$bw.Write($test)
$bw.Flush()
$bw.Dispose()
$stream.Dispose()

Upvotes: 1

stackprotector
stackprotector

Reputation: 13412

I need to pipe some data to a program's stdin.

You can indeed cause many problems when using different encodings. Here is a different approach, without any encoding applied by Get-/Set-Content.

You can actually pipe binary data to an external program by using the Start-Process cmdlet:

Start-Process my.exe -RedirectStandardInput my.bin

Works at least since PowerShell 2.0.

Upvotes: 9

anon
anon

Reputation: 39

[System.Console]::OpenStandardOutput().Write($bytes, 0, $bytes.Length)

Upvotes: 3

Bill_Stewart
Bill_Stewart

Reputation: 24525

Would this work for you?

$fileName = "C:\test.txt"
$data = [IO.File]::ReadAllText($fileName)
$prefix = ([BitConverter]::GetBytes($data.Length) | foreach-object {
  "\x{0:X2}" -f $_
}) -join ""
"{0}{1}" -f $prefix,$data

You can replace "\x{0:X2}" -f $_ with $_ -as [Char] if you want $prefix to contain the raw data representations of the bytes.

Upvotes: 2

Related Questions