PowerShell脚本问题:用哈希表替换显示器厂商缩写为全称
解决WMI自定义类中显示器厂商缩写无法替换为全称的问题
常见问题排查与修正方案
1. 哈希表匹配失败:字符格式不统一
注册表读取的厂商缩写可能带有空格、大小写不一致等问题,导致哈希表键匹配失效。需先对读取值做标准化处理:
# 读取注册表后先清理并统一为大写 $manufacturerAbbrev = $monitorRegData.Manufacturer.Trim().ToUpper()
2. 未执行替换逻辑或变量引用错误
仅定义哈希表但未将其应用到字段替换,或后续仍引用原缩写变量而非替换后的全称,是最常见的失效原因。正确的替换逻辑如下:
# 定义厂商映射哈希表 $manufacturerMap = @{ "SAM" = "Samsung" "LGD" = "LG Display" "AUO" = "AU Optronics" "BOE" = "BOE Technology Group" "CMO" = "Chi Mei Optoelectronics" } # 执行替换:存在映射则用全称,否则保留原缩写 $manufacturerFullName = if ($manufacturerMap.ContainsKey($manufacturerAbbrev)) { $manufacturerMap[$manufacturerAbbrev] } else { $manufacturerAbbrev }
3. WMI实例赋值错误
写入WMI类时,需确保使用的是替换后的全称变量,而非原缩写:
# 错误写法:仍使用原缩写 # $wmiInstance["Manufacturer"] = $manufacturerAbbrev # 正确写法:使用替换后的全称 $wmiInstance["Manufacturer"] = $manufacturerFullName
完整修正脚本示例
# 定义厂商缩写-全称映射哈希表 $manufacturerMap = @{ "SAM" = "Samsung" "LGD" = "LG Display" "AUO" = "AU Optronics" "BOE" = "BOE Technology Group" "CMO" = "Chi Mei Optoelectronics" "HWP" = "HP" } # 检查并创建WMI自定义类 $classPath = "root\cimv2:MonitorDetails" if (-not (Get-WmiObject -List -Class MonitorDetails -ErrorAction SilentlyContinue)) { $newClass = New-Object System.Management.ManagementClass("root\cimv2", $null, $null) $newClass["__CLASS"] = "MonitorDetails" $newClass.Qualifiers.Add("Static", $true) # 添加类属性 $newClass.Properties.Add("DeviceID", [System.Management.CimType]::String, $false) $newClass.Properties.Add("Manufacturer", [System.Management.CimType]::String, $false) $newClass.Properties.Add("Model", [System.Management.CimType]::String, $false) $newClass.Put() | Out-Null } # 从注册表读取显示器数据并写入WMI $monitorRegPath = "HKLM:\SYSTEM\CurrentControlSet\Enum\DISPLAY\" $monitorKeys = Get-ChildItem -Path $monitorRegPath -Recurse | Where-Object { $_.PSChildName -match "^[A-F0-9]{4}&[A-F0-9]{4}&[0-9]+&0&0&0&0&[0-9]$" } foreach ($key in $monitorKeys) { $deviceID = $key.PSParentPath.Split('\')[-1] $monitorData = Get-ItemProperty -Path $key.PSPath $model = $monitorData.MonitorModelName # 标准化厂商缩写格式 $manufacturerAbbrev = $monitorData.MonitorManufacturer.Trim().ToUpper() # 替换厂商缩写为全称 $manufacturer = if ($manufacturerMap.ContainsKey($manufacturerAbbrev)) { $manufacturerMap[$manufacturerAbbrev] } else { $manufacturerAbbrev } # 更新或创建WMI实例 $wmiInstance = Get-WmiObject -Class MonitorDetails -Filter "DeviceID='$deviceID'" -ErrorAction SilentlyContinue if ($wmiInstance) { $wmiInstance.Manufacturer = $manufacturer $wmiInstance.Model = $model $wmiInstance.Put() | Out-Null } else { $newInstance = New-Object System.Management.ManagementObject($classPath) $newInstance.DeviceID = $deviceID $newInstance.Manufacturer = $manufacturer $newInstance.Model = $model $newInstance.Put() | Out-Null } }
验证方法
执行脚本后,通过以下命令检查WMI类数据:
Get-WmiObject -Class MonitorDetails | Select-Object DeviceID, Manufacturer, Model
内容的提问来源于stack exchange,提问作者Eliran Abudi
相关产品推荐
相关产品推荐

