I'm trying to run a ping command and sorting based on "online", "offline" and "expired". I tried using find
and findstr
but I only seem to be able to sort through 2 options.
I currently have this:
ping -n 1 %ip% | find "TTL"
if errorlevel 1 set error= offline
if errorlevel 0 | find "expired"
if errorlevel 0 set error=expired
else set error=online
I'm guessing this doesn't work because the third line doesn't know where to search for "expired"? Any help would be really appreciated.
An online pc returns this:
Pinging pcName [ip] with 32 bytes of data:
Reply from ip: bytes=32 time=1ms TTL=125
Reply from ip: bytes=32 time=1ms TTL=125
Reply from ip: bytes=32 time=1ms TTL=125
Reply from ip: bytes=32 time=1ms TTL=125
Ping statistics for ip:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 1ms, Maximum = 1ms, Average = 1ms
An offline pc returns this:
Pinging pcName [ip] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.
Ping statistics for ip:
Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),
And an expired pc returns this:
Pinging pcName [ip] with 32 bytes of data:
Reply from ip: TTL expired in transit.
Reply from ip: TTL expired in transit.
Reply from ip: TTL expired in transit.
Reply from ip: TTL expired in transit.
Ping statistics for ip:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
@Aacini's answer works and is technically correct, but hard to read and to troubleshoot without a lot of experience in cmd/batch. And more importantly: it is language-dependent.
ping
is language-dependent, and I always try to find a language-independent solution (not always possible though). As with ping
, the constant through all languages is the string TTL
(never translated).
Your three example lines can easily be distinguished:
Request timed out. none of the search strings = status = "offline" (as default)
Reply from ip: bytes=32 time=1ms TTL=125 searchstring "TTL=" = overwrite status with "online"
Reply from ip: TTL expired in transit. searchstring "TTL " = overwrite status with "expired"
The code is quite intuitive and easy to read:
@echo off
setlocal
ping -4 -n 1 %ip% >ping.txt
set "status=offline"
>nul find "TTL " ping.txt && set "status=expired"
>nul find "TTL=" ping.txt && set "status=online"
echo %ip% is %status%
I didn't ever experience an "expired", but based on the output in your question, my solution should work just fine.
And more important: this is language-independent.
(I added -4
because the output using IPv6 is different - not important if you use an IPv4 Address, but will bite you when using something like "google.com" and both IPv4 AND IPv6 are enabled)