Home > Software design >  [Environment]::Is64BitProcess and [Environment]::Is32BitProcess is returning nothing
[Environment]::Is64BitProcess and [Environment]::Is32BitProcess is returning nothing

Time:01-29

I was trying to use PowerShell to detect the architecture of a computer - 32bit or 64bit.

I used to use this condition, for 64 bit:

if ([Environment]::Is64BitProcess -ne [Environment]::Is64BitOperatingSystem){}

I used to use this condition, for 32 bit:

if ([Environment]::Is32BitProcess -ne [Environment]::Is32BitOperatingSystem){}

But recently it was not working on a PC, so I tried debugging it, and it was failing everything single time. So I opened the PowerShell and tried to get what it returns for these commands. Turns out it doesn't return any Environment scope variables.

Can anyone explain to me why this is happening, and how to resolve this?

enter image description here

CodePudding user response:

You can use a small helper function that uses [Environment]::Is64BitOperatingSystem, but if not available, reverts to WMI:

function Get-Architecture {
    # What bitness does Windows use
    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   # this is slow...
        }
    }
}

Get-Architecture  # returns either `64` or `32` 

To also have it return the bitness of the PowerShell process, you can expand it to

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|ARM', '32'
    # $processBitness = if ([Environment]::Is64BitProcess) { 64 } else { 32 }

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