I'm trying to write script which will run ping command and from output it will get average latency and % of packet loss values, i tried with below command which works well
`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** `
However challenge here is i want to somehow grab just numerical vales 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 in windows, looking for help in VB or windows shell scripting which can help me to achieve my objective
TIA
@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.