ファイルを16進のダンプ形式で表示する

 以下のコードをスクリプトとして保存すると、16進数のダンプができます。スイッチパラメーターによって、以下の設定ができます。

スイッチ 意味
-NoSeparator バイトごとの空白区切りを非表示。
-NoHeader 最初の行の0〜Fを非表示。
-NoLineNumber 行番号を非表示。

スクリプト(Dump.ps1)

param
(
  [switch]$NoSeparator,
  [switch]$NoHeader,
  [switch]$NoLineNumber,
 
  [Parameter(Mandatory=$true)]
  [string]
  $LiteralPath
)

# ヘッダー表示

if(-not $NoHeader)`
{
  $builder=New-Object System.Text.StringBuilder
  if(-not $NoLineNumber)
  {
    $builder.Append("       ")> $null
  }
 
  for($i=0; $i -lt 16; $i++)`
  {
    $builder.Append($i.ToString("X")) > $null
    $builder.Append(' ') > $null
    if(-not $NoSeparator)
    {
      $builder.Append(' ') > $null
    }
  }
  $builder.ToString()
}

# ダンプ表示

$byteCount=0
$lineIndex=0
$lineIndexLength=6
$bodyBuilder=New-Object System.Text.StringBuilder

function Output([int]$lineIndex)
{
  $indexText=""
  $bodyText=$bodyBuilder.ToString()
  if(-not $NoLineNumber)
  {
    $indexText=$lineIndex.ToString(
      "X").PadLeft($lineIndexLength,'0')+" "
  }
  $bodyBuilder.Length=0
  $indexText+$bodyText
}

Get-Content $LiteralPath -Encoding byte |
  %{
    $bodyBuilder.Append(
      $_.ToString("X").PadLeft(2,'0')) > $null
    if(-not $NoSeparator)
    {
      $bodyBuilder.Append(' ') > $null
    }
   
    $byteCount=($byteCount+1)%16
   
    if($byteCount -eq 0)
    {
      Output $lineIndex
      $lineIndex++
    }
   }

if($byteCount -ne 0) { Output }

使用例

> .\Dump.ps1 .\Test.txt
       0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
000000 61 31 20 62 31 20 63 31 0D 0A 61 32 20 62 32 20
000001 63 32 0D 0A 61 32 20 62 32 20 63 33 0D 0A 61 33
000002 20 62 33 20 63 33
>
> .\Dump.ps1 .\Test.txt -NoHeader -NoLineNumber -NoSeparator
61312062312063310D0A613220623220
63320D0A61322062322063330D0A6133
206233206333
inserted by FC2 system