Powershell binary grep


Is there a way to determine whether a specified file contains a specified byte array (at any position) in powershell?

Something like:

Of course, I can write a naive implementation:

— but it’s extremely slow.


I’ve determined that the following can work as a workaround:

— i.e. any bytes can be successfully matched by PowerShell strings (in fact, .NET System.Strings) when we specify binary-safe encoding. Of course, we need to use the same encoding for both the file and fragment, and the encoding must be really binary-safe (e.g. 1250, 1000 and 28591 fit, but various species of Unicode (including the default BOM-less UTF-8) don’t, because they convert any non-well-formed code-unit to the same replacement character (U+FFFD)). Thanks to Theo for clarification.

On older PowerShell, you can use:

Sadly, I haven’t found a way to match sequences universally (i.e. a common method to match sequences with any item type: integer, object, etc). I believe that it must exist in .NET (especially that particual implementation for sequences of characters exists). Hopefully, someone will suggest it.


Powershell binary grep by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply