Checking if a binary file contains a string with PowerShell
Posted: (EET/GMT+2)
If you need to check whether a binary file contains a specific ASCII string, you can do it directly in PowerShell using .NET methods.
The idea is simple: read the file as bytes, convert to a string, and search for the value.
$path = "C:\Temp\app.exe"
$search = "MyString"
$bytes = [System.IO.File]::ReadAllBytes($path)
$text = [System.Text.Encoding]::ASCII.GetString($bytes)
if ($text.Contains($search))
{
"Match found!"
}
else
{
"No match."
}
This works well when the file contains readable ASCII text segments, for example embedded version strings or configuration values.
If you want a shorter one-liner, then you can do:
([System.Text.Encoding]::ASCII.GetString(
[System.IO.File]::ReadAllBytes("C:\Temp\app.exe")
)).Contains("MyString")
One small note: this approach loads the entire file into memory. That is fine for small or medium files, but not ideal for very large binaries.
Also, this only works reliably for ASCII or text-based content. If the data is encoded differently, you may need to adjust the encoding.
PowerShell builds on the power of .NET. Use this to your advantage. It is easy to scan binary files for simple string matches without additional tools.