Einfacher Hex-Dump mit der PowerShell
Die Windows PowerShell (liebevoll auch MachtMuschel genannt) ist eigentlich sehr nett. Natürlich nöhlen die Linux-Nutzer dass die sowas schon immer hatten und dass es ja wohl nix besonderes sei. Das leugnet ja auch keiner, aber trotzdem kann man sich an der PowerShell doch erfreuen. :-)
Heute wieder ein kleines Problem: Ich brauch einen einfachen Hex-Dump einer Datei:
PS > $str = ""; $cnt = 0; get-content -encoding byte C:\pfad\zur\Datei.txt | foreach-object { $str += (" {0:x2}" -f $_); if ($cnt++ -eq 7) { $cnt = 0; $str += "`n"; } }; write-host $str
Ist nur bedingt elegant, das gebe ich gerne zu, aber es erfüllt seinen Zweck voll und ganz. Und ist irgendwie auch nett …
A slightly more idiomatic version, without the leading space:
gc C:\pfad\zur\Datei.txt -Encoding Byte -ReadCount 8 | % { ($_ | % { „{0:x2}“ -f $_ }) -join “ “ }
Here’s one that will output a prettified hexdump with ASCII sidebar.
function Get-HexDump($bytes)
{
$chunks = [Math]::Ceiling($bytes.Length / 16);
$hexDump = 0..($chunks – 1) | %{
$bufferSize = if ($_ -ne $chunks – 1) { 16 } else { $bytes.Length – $_ * 16}
[byte[]] $buffer = @(0) * $bufferSize
[Array]::Copy($bytes, $_ * 16, $buffer, 0, $bufferSize)
$bufferChars = [System.Text.Encoding]::ASCII.GetChars($buffer);
$hexRow = ($_ * 16).ToString(„X8“) + „: “
$hexRow += (($buffer | %{ $_.ToString(„X2″) }) -join “ „)
$hexRow += (“ “ * ((17 – $buffer.Length) * 3))
$hexRow += (($bufferChars | %{ if ([char]::IsControl($_) -eq $true) { „.“ } else { „$_“ } }) -join „“)
$hexRow
}
return $hexDump
}
Just to be a Unix/Linux bitch:
hexdump
What about format-hex? Too simple?
Format-hex was introduced with Powershell 5.0 in August 2015. I wrote this article in 2013. Sadly, I am still not capable of reliably predicting future software. ;-)