Search code examples
powershellwmi

Convert CountryCode of Win32_OperatingSystem to the country string


We're trying to convert the CountryCode in to a human readable String.

Code:

$OS = Get-CimInstance -ClassName Win32_OperatingSystem

$OS | Select-Object CountryCode, OSLanguage, 
    @{N = 'OSDefaultLanguage'; E = {New-Object System.Globalization.CultureInfo([Int]$_.OSLanguage)}},
    @{N = 'OSCountryCode'; E = {New-Object System.Globalization.CultureInfo([Int]$_.CountryCode)}}

In the example above the property OSCountryCode is what we need. But it returns the value ar which is Argentina but it should return United States according to the documentation for value 1.

How can value 1 be correctly converted to US or something similar?


Solution

  • $OS = Get-CimInstance -ClassName Win32_OperatingSystem
    
    $Culture = [System.Globalization.CultureInfo]::GetCultures("SpecificCultures") | Where {$_.LCID -eq $OS.OSLanguage}
    $RegionInfo = New-Object System.Globalization.RegionInfo $Culture.Name
    
    $OS | Select-Object CountryCode, OSLanguage, 
        @{N = 'OSDefaultLanguage'; E = {New-Object System.Globalization.CultureInfo([Int]$_.OSLanguage)}},
        @{N = 'OSCountryCode'; E = {$RegionInfo.TwoLetterISORegionName}},
        @{N = 'OSCountryName'; E = {$RegionInfo.DisplayName}}