Powershell: Determine the image type (x64/x86) of an exe file

Hi,

based on this stackoverflow post I’ve written a powershell function to determine the image type of an Windows executable. The Powershells System.IO.FileSystemInfo type does not provide such an info.

function fGetImageArchitecture([string]$sFilePath)
{
	#  dos header is 64 bytes, last element, long (4 bytes) is the address of the PE header
	[int32]$MACHINE_ARCH_LENGTH = 4
	[int32]$PE_POINTER_OFFSET = 60
	[byte[]]$aData = New-Object System.Byte[] 4096
	$oFileStream = New-Object -TypeName System.IO.FileStream($sFilePath, [System.IO.FileMode]::Open,[System.IO.FileAccess]::Read)
	$oFileStream.Read($aData, 0, 4096) | Out-Null
	[int32]$PE_HEADER_ADDR = [System.BitConverter]::ToInt32($aData, $PE_POINTER_OFFSET)
	[int32]$uiArch = [System.BitConverter]::ToUInt16($aData, $PE_HEADER_ADDR + $MACHINE_ARCH_LENGTH)
	switch ($uiArch) {
		0 { return "Native" }
		0x014c { return "x86" }
		0x0200 { return "Itanium" }
		0x8664 { return "x64" }
		default {return "unknown"}
	}
}

The function needs the input file as parameter and return the image type as string

PS D:\fGetImageArchitecture $ENV:SYSTEMROOT\regedit.exe
x64

Michael

Leave a Reply