I try to write a script which runs the command ping
and get the average latency and percent of packet loss values from the output. I tried the below command which works well.
ping -n 8 4.4.4.4 >D:\latency.txt
The file D:\latency.txt
has the lines:
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
However, the challenge here is that I want to somehow grab just numerical values like 0
% loss and average 248
ms from output (so threshold can be set) and publish them in plain text file as:
Loss value in% Average value in ms
0 248
I'm not sure how to do it on Windows. I look for help in Visual Basic, PowerShell or Windows batch scripting which can help me to achieve my objective.
@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%]
Maybe a little more code than expected, but in my system (spanish locale) the loss percentage is shown in a separate line and the literals are not the same.