如何以表格格式记录 ping 统计信息?

How to record ping statistics in tabular format?

我需要在 windows 上以表格格式记录 ping 统计数据。

C:\Users\hsangal>ping localhost -t -n 2

Pinging TechBeamers.local [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

Ping statistics for 127.0.0.1:
Packets: Sent = 2, Received = 2, Lost = 0 (0% loss)
Approximate round trip times in milli-seconds:
    Minimum = 0ms, Maximum = 0ms, Average = 0ms

我想使用 Windows 批处理脚本来完成,希望专家提供一些指导。我希望以表格格式记录的数据是下面突出显示的 ping 命令输出的一部分:

Packets: Sent = 2, Received = 2, Lost = 0 (0% loss)

如果你使用 Powershell Test-Connection 命令

Test-Connection localhost

结果采用如下表格格式:

如果你想得到丢包数,你可以做下面的事情。假设您想查看 5 次 ping 中有多少丢失的数据包:

   $pingCount = 5
   $x = Test-Connection localhost -count $pingCount
   $lostPackets = $pingCount - $x.count

如果您打算编写脚本并想要格式化输出,您可能需要考虑使用 Powershell Test-Connection。它有更多选项来格式化输出。

多个输出例如: c:> 测试连接 www.google.co.za, www.yahoo.com

列选择和导出只是部分功能。 link 提供了一个很好的概述:https://technet.microsoft.com/en-us/library/hh849808.aspx

您可以使用 find 获取仅包含感兴趣信息的行,例如:

ping localhost -n 2 | find "Packets:"

这returns只有行Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),.
然后像这样环绕 for /F 语句:

for /F "tokens=3,5,7,8 delims=,=() " %I in ('ping localhost -n 2 ^| find "Packets:"') do echo %I;%J;%K;%L

输出将是这样的(发送数据包;接收数据包;丢失数据包;% loss):

2;2;0;0%

当然你可以指定除;以外的分隔符(只需在最后的echo语句中交换)。
注意上面的代码只有在直接输入命令提示符时才有效。如果要在批处理文件中使用它,请将变量 %I 等替换为 %%I.

注意: 当您提供 -n 开关时,ping 命令行中的 -t 开关将被忽略。