Hex and decimal output in PowerShell

In UNIX/Linux/whatever there is this little utility called ‘od’ which makes it trivial to dump the output of a file in multiple formats.

Yesterday, I was working on a project and needed something similar. I could’ve downloaded Cygwin and installed it, or UnixUtils from Sourceforge, but no – I decided to write a PowerShell routine to give me what I needed.

If you’ve never had the need to see hexadecimal, alphanumeric, and decimal information on a file all at once, well, move along now!

Otherwise, below is my solution for your benefit. A couple of interesting points are my use of System.Char methods to determine whether a character is printable (viewable) and my use of the format operator (-f) which uses System.Format.

Many attributes in Active Directory (including many Exchange and DNS related attributes) have a raw form that devolves into a System.Byte[] array (or an array of System.Byte[] arrays). You can get an arbitrary file as a byte array by using the Get-Content cmdlet with the “-Encoding Byte” parameter.

Here is example output (with a line of header information that isn’t from this routine):

dNSRecord contains 62 rows of type System.Byte[] from DC=_gc._tcp.E14-Site._sites,DC=essential.local,CN=MicrosoftDNS,CN=System,DC=essential,DC=local
Array contains 62 entries
26 00 21 00 05 f0 00 00 d7  &.!..ð...   38   0  33   0   5 240   0   0 215
07 00 00 00 00 02 58 00 00  ......X..    7   0   0   0   0   2  88   0   0
00 00 ac 9a 36 00 00 00 00  ....6....    0   0 172 154  54   0   0   0   0
64 0c c4 1e 03 0c 77 69 6e  d.Ä...win  100  12 196  30   3  12 119 105 110
32 30 30 38 2d 64 63 2d 33  2008-dc-3   50  48  48  56  45 100  99  45  51
09 65 73 73 65 6e 74 69 61  .essentia    9 101 115 115 101 110 116 105  97
6c 05 6c 6f 63 61 6c 00     l.local.   108   5 108 111  99  97 108   0    

And without further ado:

function dumpByteArray([System.Byte[]]$array, [int]$width = 9)
{
	$hex = ""
	$chr = ""
	$int = ""

	$i = $array.Count
	"Array contains {0} elements" -f $i
	$index = 0
	$count = 0
	while ($i-- -gt 0)
	{
		$val = $array[$index++]

		$hex += ("{0} " -f $val.ToString("x2"))

		if ([char]::IsLetterOrDigit($val) -or 
		    [char]::IsPunctuation($val)   -or 
		   ([char]$val -eq " "))
		{
			$chr += [char]$val
		}
		else
		{
			$chr += "."
		}

		$int += "{0,4:N0}" -f $val

		$count++
		if ($count -ge $width)
		{
			"$hex $chr $int"
			$hex = ""
			$chr = ""
			$int = ""
			$count = 0
		}		
	}

	if ($count -gt 0)
	{
		if ($count -lt $width)
		{
			$hex += (" " * (3 * ($width - $count)))
			$chr += (" " * (1 * ($width - $count)))
			$int += (" " * (4 * ($width - $count)))
		}

		"$hex $chr $int"
	}
}

Until next time…

If there are things you would like to see written about, please let me know!


Follow me on twitter: @EssentialExch

Leave a Reply

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