Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read/Parse Binary files with Powershell

I'm trying to parse a binary file, and I need some help on where to go. I've looking online for "parsing binary files", "reading binary files", "reading text inside binaries", etc. and I haven't had any luck.

For example, how would I read this text out of this binary file? Any help would be MUCH appreciated. I am using powershell.

enter image description here

like image 835
user1151295 Avatar asked May 20 '12 08:05

user1151295


People also ask

How do I read a .dat file in Powershell?

You can use . Net $bytes = [System. IO. File]::ReadAllBytes("<YOUR FILE>") or Powershell $bytes = Get-Content -Path "<YOUR FILE>" -Encoding Byte -Raw to read the binary data as byte array ( System.

How do I get the content of a file in Powershell?

The Get-Content cmdlet gets the content of the item at the location specified by the path, such as the text in a file or the content of a function. For files, the content is read one line at a time and returns a collection of objects, each of which represents a line of content.

How do I write to a file in Powershell?

Powershell Write Output to File. There are a couple of ways to write the output of PowerShell to a file. The most common ways are to use the Out-File cmdlet or the redirection operator > . Other options are to use the Set-Content and Add-Content cmdlet.


2 Answers

It seems that you have a binary file with text on a fixed or otherwise deducible position. Get-Content might help you but... It'll try to parse the entire file to an array of strings and thus creating an array of "garbage". Also, you wouldn't know from what file position a particular "rope of characters" was.

You can try .NET classes File to read and Encoding to decode. It's just a line for each call:

# Read the entire file to an array of bytes. $bytes = [System.IO.File]::ReadAllBytes("path_to_the_file") # Decode first 12 bytes to a text assuming ASCII encoding. $text = [System.Text.Encoding]::ASCII.GetString($bytes, 0, 12) 

In your real case you'd probably go through the array of bytes in a loop finding the start and end of a particular string sequence and using those indices to specify the range of bytes you want to extract the text from by the GetString.

The .NET methods I mentioned are available in .NET Framework 2.0 or higher. If you installed PowerShell 2.0 you already have it.

like image 183
Ferdinand Prantl Avatar answered Sep 28 '22 22:09

Ferdinand Prantl


If you're just looking for strings, check out the strings.exe utility from SysInternals.

like image 30
Keith Hill Avatar answered Sep 28 '22 21:09

Keith Hill