网络延迟监控脚本窗口

时间:2014-11-17 09:34:50

标签: windows powershell batch-file vbscript

我试图编写将运行ping命令的脚本,并且从输出中获取平均延迟和丢包率百分比值,我尝试使用下面的命令运行良好

`ping -n 8 4.4.4.4  > D:\latency.txt

C:\Users\tnt5273>ping 4.2.2.2

Pinging 4.2.2.2 with 32 bytes of data:
Reply from 4.2.2.2: bytes=32 time=253ms TTL=54
Reply from 4.2.2.2: bytes=32 time=242ms TTL=54
Reply from 4.2.2.2: bytes=32 time=252ms TTL=54
Reply from 4.2.2.2: bytes=32 time=248ms TTL=54
Reply from 4.2.2.2: bytes=32 time=253ms TTL=54
Reply from 4.2.2.2: bytes=32 time=242ms TTL=54
Reply from 4.2.2.2: bytes=32 time=252ms TTL=54
Reply from 4.2.2.2: bytes=32 time=248ms TTL=54

Ping statistics for 4.2.2.2:
    Packets: Sent = 8, Received = 8, Lost = 0 (**0% loss**),
Approximate round trip times in milli-seconds:
    Minimum = 242ms, Maximum = 253ms, Average = **248ms** `

然而,这里的挑战是我想以某种方式从输出中获取数字值(因此可以设置阈值)并将它们作为纯文本文件发布为 损失值%平均值,以毫秒为单位 0 248

,我不确定如何在Windows中执行此操作,在VB或Windows shell脚本中寻求帮助,这可以帮助我实现目标

TIA

3 个答案:

答案 0 :(得分:5)

我建议使用Test-Connection而不是ping.exe,因为它返回一个对象,您可以从中轻松获取所需的数据。

示例:

$count= 8
$con = Test-Connection 4.2.2.2 -count $count
$average = ($con.ResponseTime | Measure-Object -Average).Average
$lost = $count-($con.count)

答案 1 :(得分:1)

@echo off

for /f "tokens=3 delims=," %%# in ('ping -n 8 173.194.44.131 2^>nul^| findstr /i "loss average"') do (
    set "%%#"
)


for /f "tokens=1 delims= " %%a in ("%Average %") do echo average-%%a
for /f "tokens=2 delims=() " %%a in ("%Lost %") do echo loss-%%a

在最后两行,您可以更改输出 - %%a是值丢失,平均值是澄清字符串。您可以将结果输出到文件。

答案 2 :(得分:1)

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem Initialize variables to hold data
    set "pct="
    set "avg="

    rem Run the ping and filter to only read the required lines
    rem The first line will contain the loss percentage
    rem The second line will contain the average roundtrip
    for /f "delims=" %%a in ('
        ping -n 8 4.4.4.4 ^| findstr /r /c:"= [0-9]*ms" /c:"([0-9]*%% "
    ') do if not defined pct (

        rem Extract the % loss from the line
        for /f "tokens=2 delims=(%%" %%b in ("%%a") do set "pct=%%b"

    ) else (

        rem Retrieve the last element in the line (the average)
        for %%b in (%%a) do set "avg=%%b"
    )

    rem Remove the ms literal from the average    
    for /f "delims=m" %%a in ("%avg%") do set "avg=%%a"

    rem Echo the retrieved values
    echo pct=[%pct%] 
    echo avg=[%avg%]

可能比预期的代码多一点,但在我的系统(西班牙语语言环境)中,损失百分比显示在一个单独的行中,文字不一样。