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

求PowerShell脚本:指定源地址批量Ping服务器并输出CSV格式结果

PowerShell脚本实现指定源地址Ping服务器并输出CSV结果

你的批处理脚本失效原因

  • 嵌套循环错误:两层FOR循环都读取import.csv,导致每个目标地址会和所有源地址配对执行Ping,而非对应行的源地址,逻辑完全错误。
  • 分隔符使用错误:CSV文件默认以逗号为分隔符,但你用了delims= "(空格),会导致解析出的目标/源地址为空或错误。
  • 语法错误:批处理中变量不需要用反引号(`)包裹,ping %%D-l 0 -S%%S``是无效写法,正确应为ping %%D -l 0 -S %%S。
  • 无错误处理:如果Ping命令因权限不足、地址无效等原因失败,可能不会输出任何内容,最终导致ping.txt为空。

PowerShell解决方案

方案1:使用PowerShell原生Test-Connection cmdlet(推荐)

此方法更符合PowerShell风格,支持结构化输出,需确保PowerShell版本≥5.1且以管理员身份运行(指定源地址需要权限)。

假设你的import.csv包含表头Destination(目标地址)和Source(源地址),脚本如下:

# 定义输入输出路径
$inputCsv = "import.csv"
$outputCsv = "ping_results.csv"
$results = @()

# 读取CSV并逐行执行Ping
Import-Csv -Path $inputCsv | ForEach-Object {
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    try {
        # 执行Ping,指定源地址,发送1个数据包
        $pingResult = Test-Connection -ComputerName $_.Destination -Source $_.Source -Count 1 -ErrorAction Stop
        $status = "Success"
        $responseTime = $pingResult.ResponseTime
    }
    catch {
        $status = "Failed"
        $responseTime = $null
    }

    # 构造结果对象
    $results += [PSCustomObject]@{
        Timestamp     = $timestamp
        Destination   = $_.Destination
        SourceAddress = $_.Source
        Status        = $status
        ResponseTimeMs = $responseTime
    }
}

# 导出结果到CSV
$results | Export-Csv -Path $outputCsv -NoTypeInformation -Encoding UTF8
Write-Host "Ping结果已导出到 $outputCsv"

方案2:使用ping.exe兼容旧环境

如果无法使用管理员权限或需要兼容更低版本PowerShell,可直接调用系统ping.exe:

$inputCsv = "import.csv"
$outputCsv = "ping_results.csv"
$results = @()

# 若CSV无表头,使用-Header参数指定列名(假设第1列是目标,第3列是源)
Import-Csv -Path $inputCsv -Header "Destination", "Unused", "Source" | ForEach-Object {
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    # 执行ping命令,捕获所有输出(包括错误)
    $pingOutput = ping $_.Destination -l 0 -S $_.Source -n 1 2>&1

    if ($LASTEXITCODE -eq 0) {
        $status = "Success"
        # 从输出中提取响应时间
        $responseTime = ($pingOutput | Select-String -Pattern "time=(\d+)ms").Matches.Groups[1].Value
    }
    else {
        $status = "Failed"
        $responseTime = $null
    }

    $results += [PSCustomObject]@{
        Timestamp     = $timestamp
        Destination   = $_.Destination
        SourceAddress = $_.Source
        Status        = $status
        ResponseTimeMs = $responseTime
    }
}

$results | Export-Csv -Path $outputCsv -NoTypeInformation -Encoding UTF8
Write-Host "结果已保存到 $outputCsv"

使用说明

  1. 确保import.csv格式正确:
    • 有表头时:每行格式为Destination,Source(如8.8.8.8,192.168.1.100)
    • 无表头时:每行格式为目标地址,任意内容,源地址(对应方案2的-Header参数)
  2. 以管理员身份运行PowerShell(方案1必须,方案2视系统权限而定)
  3. 执行脚本后,结果会保存到指定的CSV文件,包含时间戳、目标地址、源地址、状态和响应时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:15:54