远程通过WMI获取[System.Globalization.CultureInfo]失败,求解决方案
解决WMI获取远程服务器Locale值为空的问题
以下是针对你的PowerShell代码中Locale列始终为空的解决办法:
先验证Locale属性的实际返回值
在循环中添加调试输出,确认$os.Locale是否真的返回了有效值。比如在获取$os对象后加入:Write-Host "服务器 $Computer 的Locale原始值: $($os.Locale)"这能帮你排查是属性本身为空,还是转换逻辑出了问题。
修正Locale的转换逻辑
Win32_OperatingSystem的Locale属性是十六进制字符串格式的LCID(比如"0409"对应英文),原代码中拼接0x再转int的方式可能在某些场景下失效。改用更可靠的十六进制解析方式,并添加空值判断:'Locale' = if ($os.Locale) { [System.Globalization.CultureInfo]::GetCultureInfo([int]::Parse($os.Locale, [System.Globalization.NumberStyles]::HexNumber)).DisplayName } else { 'Unknown' }同时添加异常捕获,避免无效Locale值导致的静默失败:
'Locale' = try { if ($os.Locale) { $lcid = [int]::Parse($os.Locale, [System.Globalization.NumberStyles]::HexNumber) [System.Globalization.CultureInfo]::GetCultureInfo($lcid).DisplayName } else { 'Unknown' } } catch { "无效Locale值: $($os.Locale)" }改用CIM替代WMI
Get-WmiObject是旧版WMI客户端,建议替换为更稳定的Get-CimInstance,它在远程访问上的兼容性和错误处理更优:$os = Get-CimInstance -Class Win32_OperatingSystem -ComputerName $Computer $tz = Get-CimInstance -Class Win32_TimeZone -ComputerName $Computer添加完整的错误处理逻辑
远程服务器可能存在离线、权限不足或WMI服务未启动的情况,添加try/catch块捕获异常,避免因为单个服务器失败导致整个脚本中断,同时明确标记异常状态:ForEach-Object { $Computer = $_.Name try { $os = Get-CimInstance -Class Win32_OperatingSystem -ComputerName $Computer -ErrorAction Stop $tz = Get-CimInstance -Class Win32_TimeZone -ComputerName $Computer -ErrorAction Stop $ntpsource = w32tm /query /computer:$Computer /source 2>&1 if ($LASTEXITCODE -ne 0) { $ntpsource = 'NTP查询失败' } $localeDisplayName = 'Unknown' if ($os.Locale) { try { $lcid = [int]::Parse($os.Locale, [System.Globalization.NumberStyles]::HexNumber) $culture = [System.Globalization.CultureInfo]::GetCultureInfo($lcid) $localeDisplayName = $culture.DisplayName } catch { $localeDisplayName = "无效Locale: $($os.Locale)" } } [PSCustomObject]@{ 'Name' = $_.Name 'Locale' = $localeDisplayName 'OS language' = Get-OSlanguage $os.OSlanguage 'TimeZone Caption' = $tz.Caption 'TimeZone StandardName' = $tz.StandardName 'TimeZone DaylightName' = $tz.DaylightName 'NTP source' = $ntpsource.Trim() } } catch { [PSCustomObject]@{ 'Name' = $_.Name 'Locale' = 'CIM访问失败' 'OS language' = 'Unknown' 'TimeZone Caption' = 'Unknown' 'TimeZone StandardName' = 'Unknown' 'TimeZone DaylightName' = 'Unknown' 'NTP source' = 'Unknown' } Write-Warning "访问服务器 $Computer 失败: $_" } }检查远程服务器的访问权限与配置
确保执行脚本的账号拥有远程服务器的管理员权限,同时确认远程服务器的:- WMI服务(Winmgmt)已启动
- 防火墙允许WMI/CIM访问(默认开放135端口及动态RPC端口)
- 未通过组策略或本地安全策略限制WMI远程访问
内容的提问来源于stack exchange,提问作者Senior Systems Engineer
相关产品推荐
相关产品推荐

