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

如何用PowerShell从CSV批量Ping IP/主机并写入状态至CSV

使用PowerShell批量Ping IP/主机并更新CSV状态列

原代码的问题分析

你的现有代码存在几个核心问题:

  • 用Get-Content读取CSV会将文件视为纯文本,无法直接解析IP/Host等结构化列
  • 依赖ping命令的文本输出做正则匹配,不如PowerShell原生的Test-Connection cmdlet便于编程判断
  • 仅处理了单一列数据,未区分IP和Host字段,也没有将结果写入CSV文件

完整解决方案

以下是能实现需求的PowerShell脚本,包含结构化解析CSV、批量Ping测试、结果写入对应列的完整流程:

# 导入CSV文件(假设CSV已有表头:IP,Host,IP_Ping_Status,Host_Ping_Status)
$hostList = Import-Csv -Path "D:\PowerShell\hostlist.csv"

# 遍历每条记录,分别测试IP和Host的连通性
foreach ($item in $hostList) {
    # 测试IP连通性:-Count 1指定发送1个包,-Quiet返回布尔值,-ErrorAction忽略解析错误
    $ipPingResult = Test-Connection -ComputerName $item.IP -Count 1 -Quiet -ErrorAction SilentlyContinue
    $item.IP_Ping_Status = $ipPingResult ? "Success" : "Failed"

    # 测试Host连通性
    $hostPingResult = Test-Connection -ComputerName $item.Host -Count 1 -Quiet -ErrorAction SilentlyContinue
    $item.Host_Ping_Status = $hostPingResult ? "Success" : "Failed"

    # 实时打印当前测试结果(可选,用于进度查看)
    Write-Host "IP: $($item.IP) [$($item.IP_Ping_Status)] | Host: $($item.Host) [$($item.Host_Ping_Status)]"
}

# 将更新后的结果导出为新CSV(避免覆盖原文件)
$hostList | Export-Csv -Path "D:\PowerShell\hostlist_updated.csv" -NoTypeInformation -Encoding UTF8

关键细节说明

  1. CSV表头处理:如果你的CSV文件没有表头,需要在Import-Csv时添加表头参数:
    $hostList = Import-Csv -Path "D:\PowerShell\hostlist.csv" -Header "IP","Host","IP_Ping_Status","Host_Ping_Status"
    
  2. 测试参数调整:可以根据需求修改Test-Connection的参数,比如:
    • -Count 4:发送4个Ping包(默认值)
    • -TimeoutSeconds 5:设置超时时间为5秒
  3. 文件导出注意:使用-Encoding UTF8确保导出的CSV支持中文等非ASCII字符;导出到新文件而非原文件,防止数据丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:37:12