Determine if current PowerShell Process is 32-bit

2019-01-10 08:47发布

问题:

When running a PowerShell script on a x64-bit OS platform, how can you determine in the script what version of PowerShell (32-bit or 64-bit) the script is running on?

Background
Both 32-bit and 64-bit versions of PowerShell are installed by default on a 64-bit platform such as Windows Server 2008. This can lead to difficulties when a PowerShell script is ran that must target a specific architecture (i.e. using 64-bit for a script for SharePoint 2010, in order to consume the 64-bit libraries).

Related question:

  • What is the best way to program against powershell's x64 vs. x86 variability? This question deals with code running against both 32-bit and 64-bit architectures. My question deals with the case when you want to ensure the script only runs against the correct version.

回答1:

If you're shell is running on .NET 4.0 (PowerShell 3.0):

PS> [Environment]::Is64BitProcess
True


回答2:

To determine in your script what version of PowerShell you're using, you can use the following helper functions (courtesy of JaredPar's answer to an related question):

# Is this a Wow64 powershell host
function Test-Wow64() {
    return (Test-Win32) -and (test-path env:\PROCESSOR_ARCHITEW6432)
}

# Is this a 64 bit process
function Test-Win64() {
    return [IntPtr]::size -eq 8
}

# Is this a 32 bit process
function Test-Win32() {
    return [IntPtr]::size -eq 4
}

The above functions make use of the fact that the size of System.IntPtr is platform specific. It is 4 bytes on a 32-bit machine and 8 bytes on a 64-bit machine.

Note, it is worth noting that the locations of the 32-bit and 64-bit versions of Powershell are somewhat misleading. The 32-bit PowerShell is found at C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe, and the 64-bit PowerShell is at C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe, courtesy of this article.



回答3:

You can use this as well. I tested it on PowerShell version 2.0 and 4.0.

$Arch = (Get-Process -Id $PID).StartInfo.EnvironmentVariables["PROCESSOR_ARCHITECTURE"];
if ($Arch -eq 'x86') {
    Write-Host -Object 'Running 32-bit PowerShell';
}
elseif ($Arch -eq 'amd64') {
    Write-Host -Object 'Running 64-bit PowerShell';
}

The value of $Arch will either be x86 or amd64.

The cool thing about doing it this way is that you can also specify a different process ID, besides the local one ($PID), to determine the architecture of a different PowerShell process.



回答4:

Switch([IntPtr]::size * 8) {

32 { <#your 32 bit stuff#> ;break }

64 { <#your 64 bit stuff#> ;break }

}