How do you read X bytes from a file without using Get-Content

Viewed 770

I want to read X bytes from a binary file via PowerShell, without using Get-Content.

I don't want to use Get-Content as the data is binary, may be large, has no line feeds, and I don't want to read any more of the file than I need to. And from googling it seems that Get-Content uses line feeds to limit how much data it reads, and I've no line feeds.

3 Answers

I don't want to use Get-Content as the data is binary, may be large, has no line feeds, and I don't want to read any more of the file than I need to

Get-Content allows you to read a limited stream of bytes from the start of the file with the -Encoding and -TotalCount parameters:

$numBytes = 10
$bytes = Get-Content .\file.bin -Encoding byte -TotalCount 10

The answer I found for this was StreamReader, and in my example below I am reading the first 10 bytes of the file (but it could easily be changed to whatever you want).

NOTE: I am reading the data into a Char array (which is fine for my needs).

    $numBytes = 10 # You'll need to test the file length is valid before reading...
    [char[]]$bytes = new-object Char[] $numBytes
    $streamReader = New-Object System.IO.StreamReader(".\fileyMcFileFile.bin")
    $countBytesGot = $streamReader.Read($bytes, 0, $numBytes) 
    $streamReader.Dispose()   

(I've answered my own question as it took me ages to work how to do this, couldn't find this solution anywhere, and thought it might help someone else).

Update to Mathias' answer for PowerShell 7.0. Instead of -Encoding Byte, you need to use -AsByteStream:

Get-Content -AsByteStream -TotalCount 0x40 output.bin | Format-Hex

Unfortunately, -AsByteStream isn't in turn available in Windows PowerShell 5.0, so if you need your script to be portable, you need to check version and do the following:

$AsByteStream = if ($PSVersionTable.PSVersion.Major -ge 7) { @{ 'AsByteStream' = $True } } else { @{ 'Encoding' = 'Byte' } }
Get-Content @AsByteStream -TotalCount 0x40 output.bin | Format-Hex
Related