确定当前的 PowerShell 进程是32位还是64位?

在 x64位操作系统平台上运行 PowerShell 脚本时,如何确定脚本运行在哪个版本的 PowerShell (32位或64位)上?

背景资料
默认情况下,PowerShell 的32位和64位版本都安装在64位平台上,如 WindowsServer2008。当运行 PowerShell 脚本时,这可能会导致困难,因为它必须针对特定的体系结构(例如,为 SharePoint 2010脚本使用64位,以便使用64位库)。

相关问题:

86815 次浏览

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.

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

PS> [Environment]::Is64BitProcess
True

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.

EDIT:

The caveat is that Process.StartInfo.EnvironmentVariables always returns the environment of the current process, no matter which process you execute it on.

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


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


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


}

With Windows itself (and PowerShell) now supported on more architectures, like ARM64, it might not always be enough to check whether the application is 64-bit.

[Environment]::Is64BitProcess will also return True on Windows running on ARM64, so you cannot rely on it if what you really need to know is whether you're running on AMD64. To do this, on Windows you can use the following environment variable:

$Env:PROCESSOR_ARCHITECTURE, which returns values like AMD64, Arm64, or x86.