PowerShell Invoke-Command查询注册表结果一致异常问题求助
问题原因及修复方案
核心错误点
- 未指定远程目标计算机:
Invoke-Command没加-ComputerName参数,导致所有命令都在本地机器执行,结果自然和本地注册表状态完全一致。 - 远程会话无法访问本地变量:
$computer.SamAccountName在远程脚本块里默认不可用,远程会话有独立的作用域,直接引用会拿不到正确值。
修复后的脚本
$ADSearchBaseComputers = 'ou=computers,ou=xxx,ou=xx,ou=xxx,dc=xx,dc=xxx,dc=xxx' # 直接提取计算机名称字符串,避免后续属性处理麻烦 $computers = Get-ADComputer -Filter * -SearchBase $ADSearchBaseComputers | Select-Object -ExpandProperty SamAccountName foreach ($computer in $computers) { # 先检测计算机是否在线,跳过无法连接的机器 if (Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction SilentlyContinue) { Invoke-Command -ComputerName $computer -ScriptBlock { $RegPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" # 用Try/Catch处理注册表项不存在的情况,避免报错中断 try { $RegName = Get-ItemProperty -Path $RegPath -Name MTBLogin -ErrorAction Stop Write-Output "Reg Key presente pour $($using:computer)" } catch { Write-Output "Reg Key non presente pour $($using:computer)" } } -ErrorAction SilentlyContinue } else { Write-Output "$computer 无法连接,跳过查询" } }
关键修改说明
- 添加
-ComputerName $computer:明确指定远程执行的目标计算机,确保查询的是对应机器的注册表。 - 使用
$using:computer:远程脚本块通过using:前缀获取本地循环中的计算机名称变量值。 ExpandProperty提取名称:直接拿到计算机名字符串,不用再处理对象属性。- 增加在线检测和错误处理:跳过离线机器,用
Try/Catch处理注册表项不存在的报错,让脚本更稳定。
内容的提问来源于stack exchange,提问作者fab
相关产品推荐
相关产品推荐

