Reading File "Magic Number"

by Aug 9, 2010

File types are not entirely dependent on file extension. Rather, binary files have internal ID numbers called "magic numbers" that tell Windows what type of file it is. Here is a function to read and display the magic number:

function Get-MagicNumber ($path)
{ Resolve-Path $path | Foreach-Object {
$magicnumber = Get-Content -encoding byte $_ -read 4 -total 4
$hex1 = ("{0:x}" -f ($magicnumber[0] * 256 + $magicnumber[1])).PadLeft(4, "0")
$hex2 = ("{0:x}" -f ($magicnumber[2] * 256 + $magicnumber[3])).PadLeft(4, "0")
[string] $chars = $magicnumber| %{ if ([char]::IsLetterOrDigit($_))
{ [char] $_ } else { "." }}
"{0} {1} '{2}'" -f $hex1, $hex2, $chars }
}

Executables use the two letters "MZ" (which coincidentally are the initials of Mark Zbikowski, one of the original developers of MS DOS). Data files use different signatures.

Twitter This Tip! ReTweet this Tip!