如何修改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"
关键说明:
- 参数配置:修改
$targetApplication、$hostsFilePath和$outputCsvPath为你的实际需求 - 系统适配:根据目标主机的操作系统(Linux/Windows)选择对应的SSH检测命令,脚本中已给出两种系统的示例
- 错误处理:SSH连接失败时会自动标记为
OFFLINE,并在控制台输出警告信息 - CSV导出:使用
UTF8编码避免中文乱码,-NoTypeInformation参数会移除CSV文件开头的类型注释行
内容的提问来源于stack exchange,提问作者SySx
相关产品推荐
相关产品推荐

