远程读取注册表时变量非空却报Null错误的技术求助
远程读取工作组Windows 7客户端PowerShell版本的脚本优化
原脚本用于读取工作组内Windows 7客户端的PowerShell版本,但存在空引用错误和逻辑判断问题,以下是修复后的版本及说明:
修复后的脚本
$ComputerName = Get-Content "C:\Users\David\Desktop\IPS.txt" $Hive = [Microsoft.Win32.RegistryHive]::LocalMachine $ps1KeyPath = 'SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine' $ps1ValueName = 'PowerShellVersion' $ps5KeyPath = 'SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine' $ps5ValueName = 'PowerShellVersion' foreach ($Computer in $ComputerName) { if (Test-Connection $Computer -Count 2 -Quiet) { try { # 仅创建一次远程注册表连接 $regBase = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $Computer) # 获取PowerShell 2.0版本,判断注册表项是否存在 $ps1Key = $regBase.OpenSubKey($ps1KeyPath) $ps1Version = if ($ps1Key) { $ps1Key.GetValue($ps1ValueName) } else { "未找到PowerShell 2.0项" } # 获取PowerShell 5.1版本,处理项不存在的情况 $ps5Key = $regBase.OpenSubKey($ps5KeyPath) $ps5Version = if ($ps5Key) { $ps5Key.GetValue($ps5ValueName) } else { "未找到PowerShell 5.1项" } # 修正逻辑判断:PS2存在且PS5版本不符合目标时标记需要更新 if ($ps1Version -eq "2.0" -and $ps5Version -ne "5.1.14409.1005") { Write-Host "$Computer 需要更新PowerShell到5.1.14409.1005" -ForegroundColor Red } else { Write-Host "`n$Computer PowerShell 2.0版本: $ps1Version" -ForegroundColor Green Write-Host "$Computer PowerShell 5.1版本: $ps5Version`n" -ForegroundColor Green } } catch { Write-Host "$Computer 远程注册表读取失败: $($_.Exception.Message)" -ForegroundColor Yellow } } else { Write-Host "$Computer 无法连通" -ForegroundColor Gray } }
关键修改说明
- 解决空引用错误:每次调用
OpenSubKey后先判断返回值是否为null,再执行GetValue;同时用try/catch捕获权限不足、连接异常等其他远程读取问题。 - 修正逻辑判断:把赋值运算符
=替换为比较运算符-eq/-ne,明确判断规则——当PowerShell 2.0存在且5.1版本不符合目标值时,标记需要更新。 - 优化资源使用:只创建一次远程注册表连接实例,避免重复建立连接消耗资源。
- 友好异常提示:针对机器不通、注册表项缺失、读取失败等场景,分别给出清晰的提示信息。
内容的提问来源于stack exchange,提问作者dweaver829
相关产品推荐
相关产品推荐

