检查多注册表键值并导出结果至CSV的PowerShell脚本问题
问题分析与脚本修正
原脚本存在的核心问题
- 路径字符串未闭合:
$Computers = Get-Content -path "LocalPath\file.txt缺少末尾双引号,导致语法错误 - 远程变量传递错误:远程脚本块中未使用
$using:作用域传递$regKey变量,远程会话无法识别该路径 - 多次远程调用的效率与变量问题:拆分获取属性和值的远程调用,导致
$properties在远程会话中不存在 - 输出格式不匹配:
Exists列是布尔值,未转换为要求的0/1数字;额外保留了Property列,不符合预期输出结构
修正后的脚本
# 读取目标计算机列表(注意路径引号闭合) $Computers = Get-Content -Path "LocalPath\file.txt" # 读取要检查的注册表键路径列表(建议单独用一个文件,避免和计算机列表混淆) $regKeyPaths = Get-Content -Path "LocalPath\RegKeys.txt" $info = ForEach ($PC in $Computers) { Write-Output "正在检查计算机: $PC" ForEach ($regKey in $regKeyPaths) { # 合并所有远程操作到一次调用,避免多次连接和变量传递问题 $remoteResult = Invoke-Command -ComputerName $PC -ScriptBlock { $targetKey = $using:regKey $keyExists = Test-Path -Path $targetKey $records = @() if ($keyExists) { $keyItem = Get-Item -Path $targetKey # 遍历键下的每个属性,生成独立记录 foreach ($prop in $keyItem.Property) { $propValue = Get-ItemPropertyValue -Path $targetKey -Name $prop $records += [PSCustomObject]@{ RegKey = $targetKey Value = $propValue Exists = [int]$keyExists } } # 处理键存在但无属性的情况 if (-not $keyItem.Property) { $records += [PSCustomObject]@{ RegKey = $targetKey Value = $null Exists = [int]$keyExists } } } else { # 键不存在时的记录 $records += [PSCustomObject]@{ RegKey = $targetKey Value = $null Exists = [int]$keyExists } } return $records } # 为每条远程记录添加计算机名称 $remoteResult | ForEach-Object { [PSCustomObject]@{ PCName = $PC RegKey = $_.RegKey Value = $_.Value Exists = $_.Exists } } } } # 导出符合要求格式的CSV $info | Select-Object PCName, RegKey, Value, Exists | Export-Csv -Path "LocalPath\Output.csv" -NoTypeInformation
关键修改说明
- 语法修复:补全路径字符串的闭合引号,将注册表键路径单独存放,避免和计算机列表混淆
- 远程调用优化:将所有远程操作合并到一个
Invoke-Command中,减少远程连接开销,同时解决变量跨会话传递问题 - 格式匹配:将
Exists的布尔值转换为整数(0/1),移除多余的Property列,严格匹配要求的输出结构 - 边界处理:新增对「键存在但无属性」场景的处理,确保记录完整性
内容的提问来源于stack exchange,提问作者MjrPayne
相关产品推荐
相关产品推荐

