Skip to content

Instantly share code, notes, and snippets.

@fdcastel
Created June 17, 2025 02:45
Show Gist options
  • Save fdcastel/8f37d01c5cbca5a8de85cc94814192e1 to your computer and use it in GitHub Desktop.
Save fdcastel/8f37d01c5cbca5a8de85cc94814192e1 to your computer and use it in GitHub Desktop.
Powershell script to display a hex dump of a file's contents.
function Write-HexDump {
<#
.SYNOPSIS
Displays a hex dump of a file's contents.
.PARAMETER FilePath
Path to the file to display as a hex dump.
.PARAMETER ByteCount
Number of bytes to read and display. Default is 256.
.PARAMETER StartOffset
Position of the first byte to read from the file. Default is 0.
.EXAMPLE
Write-HexDump -FilePath '/data/file.bin' -ByteCount 128 -StartOffset 16
.NOTES
Original code dreated by Claude Sonnet 4
#>
param(
[string]$FilePath,
[int]$ByteCount = 256,
[int]$StartOffset = 0
)
$offsetColor = 'Blue'
$hexColor = 'Green'
$asciiColor = 'Gray'
$bytes = [byte[]]::new($ByteCount)
$fileStream = [System.IO.File]::OpenRead($FilePath)
try {
$null = $fileStream.Seek($StartOffset, [System.IO.SeekOrigin]::Begin)
$bytesRead = $fileStream.Read($bytes, 0, $ByteCount)
# Print header
Write-Host 'Offset ' -NoNewline -ForegroundColor "Dark$offsetColor"
Write-Host '00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ' -NoNewline -ForegroundColor "Dark$hexColor"
Write-Host ' ASCII' -ForegroundColor "Dark$asciiColor"
Write-Host '-------- ' -NoNewline -ForegroundColor "Dark$offsetColor"
Write-Host '------------------------------------------------ ' -NoNewline -ForegroundColor "Dark$hexColor"
Write-Host '-----------------' -ForegroundColor "Dark$asciiColor"
$firstCol = $StartOffset % 16
$totalRows = [Math]::Ceiling(($bytesRead + $firstCol) / 16)
for ($row = 0; $row -lt $totalRows; $row++) {
$rowOffset = $row * 16
$hexBuilder = [System.Text.StringBuilder]::new()
$asciiBuilder = [System.Text.StringBuilder]::new()
for ($col = 0; $col -lt 16; $col++) {
$byteIndex = $rowOffset + $col - $firstCol
if (($row -eq 0) -and ($col -lt $firstCol)) {
$null = $hexBuilder.Append(' ')
$null = $asciiBuilder.Append(' ')
} elseif ($byteIndex -ge 0 -and $byteIndex -lt $bytesRead) {
$b = $bytes[$byteIndex]
$null = $hexBuilder.AppendFormat('{0:X2} ', $b)
$c = if ([System.Char]::IsControl($b)) { '.' } else { [char]$b }
$null = $asciiBuilder.Append($c)
} else {
$null = $hexBuilder.Append(' ')
$null = $asciiBuilder.Append(' ')
}
# Add space after 8th byte for readability
if ($col -eq 7) {
$null = $hexBuilder.Append(' ')
$null = $asciiBuilder.Append(' ')
}
}
# Print row offset
Write-Host ('{0:X8} ' -f $rowOffset) -NoNewline -ForegroundColor $offsetColor
# Print hex representation
Write-Host $hexBuilder.ToString() -NoNewline -ForegroundColor $hexColor
# Print ASCII representation
Write-Host $asciiBuilder.ToString() -ForegroundColor $asciiColor
}
} finally {
$fileStream.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment