如何使用Powershell检查OS架构(32或64位)?

时间:2020-04-23 20:30:17

标签: windows powershell

我正在编写Powershell脚本,该脚本将集成到为32位Windows计算机设计的产品中。因此,默认情况下,即使在64位计算机上,它也将在x86 Powershell上运行。 我尝试使用[System.IntPtr]::Size,但是输出与同一台计算机上的Powershell版本不同。

Powershell(32位)-

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

同一台计算机上的Powershell(64位)-

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

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

2 个答案:

答案 0 :(得分:2)

感谢BACONthis answer的一个密切相关的问题的链接,以下简洁的解决方案是可能的,该解决方案适用于 32位和64位PowerShell会话:

$pointerSizeInBytes = (4, 8)[[Environment]::Is64BitOperatingSystem]

[bool]值解释为数组索引[int])映射到0$false)或{{ 1}}(1),此处用于从数组$true中选择适当的值。


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


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

4, 8

64位系统上的32位进程(仅)将$is64Bit = Test-Path C:\Windows\SysNative 的64位SYSTEM32(sic)目录视为{sup>

但是,以下 32位和64位会话中均可使用

C:\Windows\SysNative

仅在64位系统上,自动定义的$is64Bit = Test-Path 'Env:ProgramFiles(x86)' 环境变量与ProgramFiles(x86)变量并存。

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

ProgramFiles

$pointerSizeInBytes = (4, 8)[[bool] ${env:ProgramFiles(x86)}] 使用namespace variable notation返回env的值。变种直接${env:ProgramFiles(x86)};将字符串值强制转换为ProgramFiles(x86)仅对非空字符串返回[bool];被解释为数组索引$true)的[bool]映射到[int]0)或$false({{1 }}),此处用于从数组1中选择适当的值。

答案 1 :(得分: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进程的“位数”以及操作系统的位数,如:

ProcessArchitecture WindowsArchitecture
------------------- -------------------
64 bit              64 bit   
相关问题