如何使用Powershell检查操作系统架构(32位或64位)?

4

我正在编写一段 Powershell 脚本,将其集成到专为 32 位 Windows 机器设计的产品中。因此,在调用时,即使在 64 位机器上,它也将默认在 x86 Powershell 上运行。

我尝试使用 [System.IntPtr]::Size,但输出结果与同一台机器上的 Powershell 版本不同。

Powershell(32 位) -

PS D:\powershellScripts>  [System.IntPtr]::Size    
4

在同一台机器上使用64位Powershell-

PS D:\powershellScripts> [System.IntPtr]::Size
8

我需要一个独立的解决方案,可以帮助我区分底层计算机的地址大小。


1
这个回答解决了您的问题吗?在Powershell中确定32/64位 - Lance U. Matthews
2个回答

7
感谢 BACON 提供的链接,指向一个与这个问题密切相关的问题,并附有此答案。由此得到了以下简洁的解决方案,适用于 32位和64位 PowerShell 会话:
$pointerSizeInBytes = (4, 8)[[Environment]::Is64BitOperatingSystem]
[bool]值被解释为数组索引([int]),映射到0($false)或1($true),用于从数组4,8中选择适当的值。

这是原始答案的形式,其中可能有一些相关信息:


一个简单的测试,假设您始终在32位PowerShell实例上运行:

$is64Bit = Test-Path C:\Windows\SysNative

64位系统上仅限32位进程将64位SYSTEM32目录视为 C:\Windows\SysNative

然而,以下内容适用于32位和64位会话

$is64Bit = Test-Path 'Env:ProgramFiles(x86)'

只有在64位系统上,ProgramFiles(x86)环境变量才会自动定义并与ProgramFiles变量并存。

获取操作系统本机指针大小(以字节为单位)

$pointerSizeInBytes = (4, 8)[[bool] ${env:ProgramFiles(x86)}]

${env:ProgramFiles(x86)}使用命名空间变量符号直接返回环境变量ProgramFiles(x86)的值;将字符串值转换为[bool]仅对非空字符串返回$true;将[bool]解释为数组索引[int])映射到0$false)或1$true),这里用于从数组4,8中选择适当的值。


0

另一种方法是将其包装在一个小的辅助函数中:

function Get-Architecture {
    # What bitness does Windows use
    $windowsBitness = switch ([Environment]::Is64BitOperatingSystem) {   # needs .NET 4
        $true  { 64; break }
        $false { 32; break }
        default {
            (Get-WmiObject -Class Win32_OperatingSystem).OSArchitecture -replace '\D'
            # Or do any of these:
            # (Get-WmiObject -Class Win32_ComputerSystem).SystemType -replace '\D' -replace '86', '32'
            # (Get-WmiObject -Class Win32_Processor).AddressWidth   # slow...
        }
    }

    # What bitness does this PowerShell process use
    $processBitness = [IntPtr]::Size * 8
    # Or do any of these:
    # $processBitness = $env:PROCESSOR_ARCHITECTURE -replace '\D' -replace '86', '32'
    # $processBitness = if ([Environment]::Is64BitProcess) { 64 } else { 32 }

    # Return the info as object
    return New-Object -TypeName PSObject -Property @{
        'ProcessArchitecture' = "{0} bit" -f $processBitness
        'WindowsArchitecture' = "{0} bit" -f $windowsBitness
    }
}

Get-Architecture

此命令将返回当前正在运行的 PowerShell 进程的“位数”,以及操作系统的“位数”,如下所示:

进程架构 Windows 架构
------------------- -------------------
64 位              64 位

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接