Simple Hex-Dump using the PowerShell

The Windows Powershell is quite nice. Of course, now all the Linux users start bitching around, that they always has something like this and that it is nothing special. And no one claims otherwise. But still, the PowerShell is nice and I enjoy it. 🙂

Like today: I needed a simple hex dump of a file:

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

It’s elegance is limited, that I will admit, however, I does it’s job. And, somehow, it is quite nice …

Tagged with:
5 comments on “Simple Hex-Dump using the PowerShell
  1. Rickard says:

    A slightly more idiomatic version, without the leading space:

    gc C:\pfad\zur\Datei.txt -Encoding Byte -ReadCount 8 | % { ($_ | % { “{0:x2}” -f $_ }) -join ” ” }

  2. James Coe says:

    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
    }

  3. Eku says:

    Just to be a Unix/Linux bitch:

    hexdump

  4. name says:

    What about format-hex? Too simple?

    • SGrottel says:

      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. 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.