Displaying Hex Dumps

by Aug 10, 2010

PowerShell can read plain text, but it can also read binary content. Here is a little function that creates a "hex dump" of any binary file:

function Get-HexDump($path,$width=10, $bytes=-1)
{
$OFS=""
Get-Content -Encoding byte $path -ReadCount $width `
-totalcount $bytes | Foreach-Object {
$byte = $_
if (($byte -eq 0).count -ne $width)
{
$hex = $byte | Foreach-Object {
" " + ("{0:x}" -f $_).PadLeft(2,"0")}
$char = $byte | Foreach-Object {
if ([char]::IsLetterOrDigit($_))
{ [char] $_ } else { "." }}
"$hex $char"
}
}
}

And this is an example on how to call the function:

get-hexdump $env:windir\explorer.exe -width 15 -bytes 150

Twitter This Tip! ReTweet this Tip!