获取远程服务器已装应用:先检测注册表项再执行对应命令
调整后的PowerShell脚本方案
针对你遇到的注册表路径不存在报错问题,以下是调整后的脚本,实现先检测注册表项存在性,再选择对应获取方式的逻辑:
# 指定目标服务器 $ComputerName = "ServerName001" $ScriptPath = Get-Location # 定义输出文件路径 $RegOutputPath = Join-Path -Path $ScriptPath -ChildPath "$ComputerName_Registry_InstalledApps.csv" $WmiOutputPath = Join-Path -Path $ScriptPath -ChildPath "$ComputerName_Wmi_InstalledApps.csv" $results = Invoke-Command -ComputerName $ComputerName -ScriptBlock { # 定义注册表路径 $regPath32 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $regPath64 = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" # 检测路径是否存在 $has32BitReg = Test-Path $regPath32 $has64BitReg = Test-Path $regPath64 $appsFromRegistry = @() # 收集32位注册表中的应用 if ($has32BitReg) { $appsFromRegistry += Get-ItemProperty "$regPath32\*" | Where-Object { $_.DisplayName } Write-Output "已获取32位注册表中的应用列表" } else { Write-Output "未找到32位Uninstall注册表路径" } # 收集64位注册表中的应用 if ($has64BitReg) { $appsFromRegistry += Get-ItemProperty "$regPath64\*" | Where-Object { $_.DisplayName } Write-Output "已获取64位注册表中的应用列表" } else { Write-Output "未找到64位Uninstall注册表路径" } # 如果注册表中有数据,返回整理后的结果;否则返回$null触发WMI逻辑 if ($appsFromRegistry.Count -gt 0) { $appsFromRegistry | Select-Object -Property DisplayName, Publisher, DisplayVersion, InstallDate, InstallLocation, PSComputerName } else { Write-Output "注册表中未找到任何应用记录,将使用WMI获取" $null } } # 处理返回结果:如果注册表有数据则导出,否则执行WMI查询并导出 if ($results -and $results.Count -gt 0) { $results | Export-Csv -Path $RegOutputPath -NoTypeInformation -Encoding utf8 Write-Output "注册表应用列表已导出到: $RegOutputPath" } else { Get-WmiObject -Query "select * from win32_product" -ComputerName $ComputerName | Select-Object -Property Name, Vendor, Version, PSComputerName | Export-Csv -Path $WmiOutputPath -NoTypeInformation -Encoding utf8 Write-Output "WMI应用列表已导出到: $WmiOutputPath" }
关键修改说明
- 避免路径不存在报错:使用
Test-Path检测注册表路径的存在性,替代原脚本中直接调用Get-ChildItem的方式,彻底解决路径不存在时的异常 - 过滤无效项:添加
Where-Object { $_.DisplayName }筛选,排除无显示名称的注册表残留项或系统组件,让结果更精准 - 规范路径拼接:用
Join-Path替代字符串拼接生成输出文件路径,避免因路径格式问题导致的导出失败 - 逻辑整合:优先从注册表获取应用数据,只有当注册表无有效记录时,才自动触发
Get-WmiObject查询,符合你要求的 fallback 逻辑 - 清晰的输出提示:添加了运行状态提示,方便排查执行过程中的问题
内容的提问来源于stack exchange,提问作者duxck
相关产品推荐
相关产品推荐

