Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Determine if a process is 32 or 64 bit

Is there a way to determine if a given process ID is for a 32 or a 64 bit process? I'm using Powershell v3.0

like image 915
Zain Rizvi Avatar asked Apr 12 '14 00:04

Zain Rizvi


People also ask

How can I tell if a Windows process is 64-bit?

Note: If System isn't listed under Control Panel in the search results, click Control Panel to see more results. Under System, look at the System type entry. It will say either 32-bit Operating System or 64-bit Operating System.

Is PowerShell x86 or x64?

When you run Windows PowerShell, the 64-bit version runs by default. However, you might occasionally need to run Windows PowerShell (x86), such as when you're using a module that requires the 32-bit version or when you're connecting remotely to a 32-bit computer.


2 Answers

Try this:

Add-Type -MemberDefinition @'
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(
    [In] System.IntPtr hProcess,
    [Out, MarshalAs(UnmanagedType.Bool)] out bool wow64Process);
'@ -Name NativeMethods -Namespace Kernel32

Get-Process -Id $id | Foreach {
    $is32Bit=[int]0 
    if ([Kernel32.NativeMethods]::IsWow64Process($_.Handle, [ref]$is32Bit)) { 
        "$($_.Name) $($_.Id) is $(if ($is32Bit) {'32-bit'} else {'64-bit'})" 
    } 
    else {"IsWow64Process call failed"}
}

There should be a check in here to ensure the OS is 64-bit otherwise all processes would be 32-bit.

like image 57
Keith Hill Avatar answered Sep 23 '22 21:09

Keith Hill


Building on Keith Hill's excellent solution:

Below is the source code for the Get-32BitProcess function, a wrapper around Get-Process that reports 32-bit processes only.

Caveats:

  • Only local processes are supported, so the -ComputerName parameter is not supported. Parameters -Module and -FileVersionInfo aren't supported either, but you can just pipe to a Get-Process call with these parameters.

  • Testing the bitness of a process created by a different user requires elevation (running as administrator), so to examine all 32-bit processes, run with elevation.
    If you run without elevation, you're warned that only the current user's processes can be targeted; use -WarningAction SilentlyContinue to silence the warning.

  • Since the distinction between 32-bit and 64-bit processes only makes sense on 64-bit editions of Windows, the function refuses to run on 32-bit editions - simply use Get-Process there.

To use it to solve the OP's problem, using the example of the current process ($PID):

$is32Bit = [bool] (Get-32BitProcess -ID $PID)

That is, given a valid PID (process ID), Get-32BitProcess outputs a [System.Diagnostics.Process] object representing the process, as reported Get-Process if the target process is 32-bit; if it is a 64-bit process, nothing is output.

To simply list all running 32-bit processes (with elevation: system-wide; without elevation: created by the current user):

Get-32BitProcess

Get-32BitProcess source code:

function Get-32BitProcess {
<#
.SYNOPSIS
Gets 32-bit processes running on the local 64-bit Windows computer.

.DESCRIPTION
By default, all accessible 32-bit processes are returned:

- Without elevation, you're limited to querying processes created in the context
  of the current user, and a warning to that effect is displayed.

- With elevation, all system-wide 32-bit processes are output; inaccessible
  system process (which are inherently 64-bit) are ignored.
  To see which ones are ignored, pass -Verbose.

This function is in effect a filtering wrapper around Get-Process that only
operates on 32-bit processes.

Parameters are the same as for Get-Process, with the following exceptions:

* only *local* 32-bit processes can be retrieved, so the -ComputerName parameter 
  is not supported.

* parameters -FileVersionInfo and -Module are not supported; however, you 
  can simply pipe this function's output to a Get-Process call with these
  parameters.

Note that you'll only get output for a given process if it is indeed a 32-bit
process; when in doubt, pass -Verbose.

.NOTES
Inspired by https://stackoverflow.com/a/23025963/45375

Refuses to run on 32-bit editions of Windows, because the distinction between
32-bit and 64-bit is only meaningful in 64-bit editions.

.LINK
Get-Process

.EXAMPLE
> Get-32BitProcess
With elevation: outputs all 32-bit processes.
Without elevation: outputs the current user's 32-bit processes.

.EXAMPLE
> Get-32BitProcess -ID $PID
Implicitly tests if the current process is 32-bit: if it is, information about
the process is output; if not, there's no ouptut.
#>
  [CmdletBinding(DefaultParameterSetName='Name')]
  param(
    [Parameter(ParameterSetName='NameWithUserName', Position=0, ValueFromPipelineByPropertyName=$true)]
    [Parameter(ParameterSetName='Name', Position=0, ValueFromPipelineByPropertyName=$true)]
    [Alias('ProcessName')]
    [ValidateNotNullOrEmpty()]
    [string[]]
    ${Name},

    [Parameter(ParameterSetName='Id', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [Parameter(ParameterSetName='IdWithUserName', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [Alias('PID')]
    [int[]]
    ${Id},

    [Parameter(ParameterSetName='InputObject', Mandatory=$true, ValueFromPipeline=$true)]
    [Parameter(ParameterSetName='InputObjectWithUserName', Mandatory=$true, ValueFromPipeline=$true)]
    [System.Diagnostics.Process[]]
    ${InputObject},

    [Parameter(ParameterSetName='IdWithUserName', Mandatory=$true)]
    [Parameter(ParameterSetName='NameWithUserName', Mandatory=$true)]
    [Parameter(ParameterSetName='InputObjectWithUserName', Mandatory=$true)]
    [switch]
    ${IncludeUserName}
  )

  if ($env:OS -ne 'Windows_NT') { Throw "This function runs on Windows only." }
  if (-not ${env:ProgramFiles(x86)}) { Throw "This function runs on 64-bit editions of Windows only."}

  # Define the helper type that provides access to the IsWow64Process 
  # Windows API function.
  # Calling this repeatedly in a session is idempotent, as long as the 
  # type definition doesn't change.
  Add-Type -MemberDefinition @'
    [DllImport("kernel32.dll")]
    public static extern bool IsWow64Process(System.IntPtr hProcess, [Out] out bool wow64Process);
'@ -Name NativeMethods -Namespace Kernel32

  [bool] $is32Bit = $False

  $isElevated = ([System.Security.Principal.WindowsPrincipal] [System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole('Administrators')
  if (-not $isElevated) {
    Write-Warning "Running without elevation: Output is limited to the current user's 32-bit processes."
  }

  # Pass the pipeline input / arguments through to Get-Process and collect all
  # resulting [System.Diagnostics.Process] instances.
  # Note that since we rely on inspecting the .Handle property of 
  # [System.Diagnostics.Process] instances, we don't support the -FileVersionInfo
  # and -Module parameters, because they output objects of different types.
  if ($MyInvocation.ExpectingInput) {
    # If there's pipeline input, we must remove the pipeline-binding parameters
    # from $PSBoundParameters to avoid a collisions.
    $null = foreach ($param in 'InputObject', 'Id', 'Name') {
      $PSBoundParameters.Remove($param)
    }
    $processes = $Input | Microsoft.PowerShell.Management\Get-Process @PSBoundParameters
  } else {
    $processes = Microsoft.PowerShell.Management\Get-Process @PSBoundParameters
  }

  # Now filter the result objects by removing non-32-bit processes.
  [bool] $is32Bit = $false
  foreach ($ps in $processes) {
      if (-not $ps.Handle) {
        # Without elevation, many processes cannot be accessed, and some
        # cannot even be accessed with elevation (e.g., 'services')
        Write-Verbose "Access to process handle denied: $($ps.Name) ($($ps.ID))"
      } elseif (-not ([Kernel32.NativeMethods]::IsWow64Process($ps.Handle, [ref]$is32Bit))) {
        Write-Error "IsWow64Process() Windows API call failed for ID $($ps.ID)" # should never happen
      } elseif ($is32Bit) { # a 32-bit process: output it
        $ps
      } else {
        Write-Verbose "Not a 32-bit process: $($ps.Name) ($($ps.ID))"
      }
  }

}
like image 27
mklement0 Avatar answered Sep 22 '22 21:09

mklement0