You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取远程服务器已装应用:先检测注册表项再执行对应命令

调整后的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 14:20:56