0

Can anyone show me how to verify multiple outputs in .bat file.

I'm using

@echo off
:start
ping x.x.x.x | findstr "unreachable" > nul
if %errorlevel% == 0 (
    echo "Network disconnect"
    goto RestartLAN
) else (
    echo "OK"
)
goto start

In this code I verify "unreachable" so how can I extend the line ping 10.128.224.1 | findstr "unreachable" > nul to verify output "timeout", "general failure" as well.

John DOE
  • 400
  • 1
  • 3
  • 18
realheaven
  • 295
  • 1
  • 3
  • 8

3 Answers3

1

Put ping output into a text file and do multiple findstr. If you don't care which error then findstr will search all terms seperated by spaces. findstr "timeout unreachable" will match either (although you should be specifing switches to make intentions clear).

Ping returns 0 for error and 1 for success (wierd I know).

ping 128.0.0.1 && Echo Error (but for other commands means success) || Echo Success (but for other commands means error)

This is reverse of normal practise where 0 means success.

Findstr also returns error codes. 0 = Found, 1 = Not Found, and 2 = Error.

ping 128.0.0.1 | findstr /i /c:"unreachable"
If errorlevel 0 if not errorlevel 1 Echo Findstr found host unreachable
If errorlevel 1 if not errorlevel 2 Echo Findstr didn't find unreachable
If errorlevel 2 if not errorlevel 3 Echo Cmd has badly screwed up file redirection else you'll never see this
Serenity
  • 433
  • 2
  • 4
  • There is an error in your answer. For ipv4, ping sets errorlevel when at least one packet is lost and does not set errorlevel when no packet is lost. – MC ND Jan 14 '15 at 07:06
1
(ping x.x.x.x | find "TTL=" >nul) && (echo OK) || (echo FAILURE)

For ipv4, if the output contains the string TTL= the target machine is reachable.

Here you can find more information on the ping usage.

Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Thanks MC ND for your suggest to check the string "TTL". It solves my case to check network connection. Also thanks to Serenity for detail Found = 0. `:start` `ping x.x.x.x | findstr "TTL=" > nul` `if %errorlevel% == 0 (` ` echo "OK"` `) else (` ` echo "Network Failure. Restart LAN"` ` goto RestartLAN` `)` `goto start` – realheaven Jan 16 '15 at 03:26
0

Demo:

@ECHO OFF
SETLOCAL

FOR %%a IN ("unreachable" "timeout" "general failure" "fine and dandy") DO (
 ECHO %%~a|FINDSTR /c:"unreachable" /c:"timeout" /c:"general failure" >NUL
 CALL ECHO ERRORLEVEL %%errorlevel%% FOR %%~a
)

GOTO :EOF

so,

ping x.x.x.x | FINDSTR /c:"unreachable" /c:"timeout" /c:"general failure" >NUL

should fit your situation.

Magoo
  • 77,302
  • 8
  • 62
  • 84