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

如何修改PowerShell脚本,将多主机应用检测结果导出为双列CSV?

PowerShell SSH批量检测应用并导出CSV结果

以下是修改后的脚本,可实现批量通过SSH检测主机应用安装状态,并将结果导出为包含「Hostname」和「Result」列的CSV文件,Result列会返回YES(已安装)、NO(未安装)或OFFLINE(连接失败):

# 配置参数
$targetApplication = "nginx"  # 替换为你要检测的应用名称
$hostsFilePath = ".\hosts.txt"  # 主机列表文件路径(每行一个主机名/IP)
$outputCsvPath = ".\AppDetectionResult.csv"

# 初始化结果数组
$detectionResults = @()

# 遍历所有主机
foreach ($hostName in Get-Content -Path $hostsFilePath) {
    # 创建结果对象,默认标记为OFFLINE
    $currentResult = [PSCustomObject]@{
        Hostname = $hostName.Trim()
        Result   = "OFFLINE"
    }

    try {
        # 根据目标主机系统选择检测命令:
        # Linux系统示例(Debian/Ubuntu用dpkg,RHEL/CentOS可替换为`rpm -qa | grep -q $targetApplication && echo YES || echo NO`)
        $sshCommand = "dpkg -l | grep -q $targetApplication && echo YES || echo NO"
        
        # Windows系统示例(需目标主机开启SSH并支持PowerShell)
        # $sshCommand = "Get-Command $targetApplication -ErrorAction SilentlyContinue; if (`$?) { echo YES } else { echo NO }"

        # 执行SSH命令并捕获输出
        $commandOutput = ssh $hostName $sshCommand
        
        # 根据命令执行结果更新状态
        if ($LASTEXITCODE -eq 0) {
            $currentResult.Result = $commandOutput.Trim()
        }
    }
    catch {
        # 连接失败时保留OFFLINE状态,同时输出警告日志
        Write-Warning "主机 $hostName 连接失败:$($_.Exception.Message)"
    }

    # 将当前主机结果加入数组
    $detectionResults += $currentResult
}

# 导出结果到CSV文件
$detectionResults | Export-Csv -Path $outputCsvPath -NoTypeInformation -Encoding UTF8
Write-Host "检测完成,结果已导出至 $outputCsvPath"

关键说明:

  1. 参数配置:修改$targetApplication、$hostsFilePath和$outputCsvPath为你的实际需求
  2. 系统适配:根据目标主机的操作系统(Linux/Windows)选择对应的SSH检测命令,脚本中已给出两种系统的示例
  3. 错误处理:SSH连接失败时会自动标记为OFFLINE,并在控制台输出警告信息
  4. CSV导出:使用UTF8编码避免中文乱码,-NoTypeInformation参数会移除CSV文件开头的类型注释行

内容的提问来源于stack exchange,提问作者SySx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:31:04