0

I'm trying to check response from list of n-thousand IPs using ping command via windows batch script and save all results in a file (yes if response and no if don't). Is this even possible via batch script? When I'm using script printed below (pingingN.bat) I'm getting only first IP answer.

@ECHO OFF

SET ServerList="C:\MyPath\ip.txt"
SET LogFile="C:\MyPath\PingResults.txt"

IF EXISTS %LogFile% DEL %LogFile%

FOR %%a IN (%ServerList%) DO (
    ping -n 1 %%a | find "TTL=" > NUL
    IF %ERRORLEVEL% NEQ 0 (
        echo no >> %LogFile%
    ) ELSE (
        echo yes >> %LogFile%
    )
)
akei9
  • 45
  • 1
  • 3
  • 12
  • To answer your question: yes, it is possible. Anyway, in your code you need [delayed expansion](http://ss64.com/nt/delayedexpansion.html) for `ErrorLevel`, so that `%ErrorLevel%` becomes `!ErrorLevel!`, or you change `if %ErrorLevel% neq 0` to `if ErrorLevel 1` (meaning *if ErrorLevel is equal to or greater than 1*), as `ping` does not return a negative `ErrorLevel` anyway... – aschipfl Jul 17 '18 at 07:52
  • Also `SET ServerList="C:\MyPath\ip.txt"` should be `SET "ServerList=C:\MyPath\ip.txt"`, `SET LogFile="C:\MyPath\PingResults.txt"` should be `SET "LogFile=C:\MyPath\PingResults.txt"`, `IF EXISTS %LogFile% DEL %LogFile%` should be `IF EXIST "%LogFile%" DEL "%LogFile%"` and `FOR %%a IN (%ServerList%) DO (` should be `FOR /F UseBackQ %%a IN ("%ServerList%") DO (`. – Compo Jul 17 '18 at 08:36

3 Answers3

0

you can use delayed Expansion or if errorlevel (as commented by aschipfl) or use another approach:

(FOR %%a IN (%ServerList%) DO (
   ping -n 1 %%a | find "TTL=" > NUL && (
      echo %%a, yes
   ) || (
      echo %%a, no
   )
)>%LogFile%

where && means "if previous command (find) was successful then" and || "if previous command (find) failed then"

Just redirecting once the whole output instead of each line on it's own gives you a big speed boost.

Stephan
  • 53,940
  • 10
  • 58
  • 91
0

Based on my comment and using the && and || conditionals, here's how I would do it:

@Echo Off

Set "ServerList=C:\MyPath\ip.txt"
Set "LogFile=C:\MyPath\PingResults.txt"

If Not Exist "%ServerList%" Exit /B
>"%LogFile%" (For /F UseBackQ %%A In ("%ServerList%"
) Do Ping -n 1 %%A|Find "TTL=">Nul&&(Echo Yes [%%A])||Echo No [%%A])

You'll note that I have also included the IP in the output, otherwise your log file will not show you which ones did or didn't pass/fail.

Compo
  • 36,585
  • 5
  • 27
  • 39
0
  1. Create a file (test.txt) and list down all the IPs you want to ping.
  2. Create another bat.file and write this command.

(for /F %i in (test.txt) do ping -n 1 %i 1>nul && echo %i UP || echo %i DOWN ) 1>result.txt

  1. Run this command, It will list down which IP is up and which one is down.