I would like to make a .bat file that will do a for loop like below:
@echo off
FOR /L %%G IN (1, 1, 69) DO (
ping -n 1 192.168.%%G.3
ping -n 1 192.1
@echo off
:A
FOR /L %%G IN (1, 1, 69) DO (
ping -n 1 192.168.%%G.3
ping -n 1 192.168.%%G.4
)
:GoTo
@ECHO OFF
SET output=%USERPROFILE%\output.txt
IF EXIST "%output%" DEL "%output%"
FOR /L %%G IN (1, 1, 69) DO (
CALL :ping 192.168.%%G.3
CALL :ping 192.168.%%G.4
)
GOTO :EOF
:ping
ping -n 1 %1 >NUL && ECHO %1>>"%output%"
Basically, you use &&
to add the command that is only executed if the previous command (the one before the &&
) completed successfully (technically speaking, returned the exit code of 0
).
There's a similar approach for the opposite case. If you want to perform some actions on the unsuccessful result of a command, you put ||
after it and then the command implementing your action.
EDIT
One note about ping
. Sometimes you get a notification from the router that the host is not accessible. In this case ping
still exits with 0
code ('successful'), because it does get a reply, even if it's from the router and not from the actual host.
If that can be the case with your hosts and you don't want to have such false positives in the output file, you'll have to parse the output of ping
for some keywords indicating whether the pinging was successful indeed. So far you can rely on the lines showing the aggregate stats: they only appear if the reply was from the intended host.
So, here's the alternative approach:
@ECHO OFF
SET output=%USERPROFILE%\output.txt
IF EXIST "%output%" DEL "%output%"
FOR /L %%G IN (1, 1, 69) DO (
CALL :ping 192.168.%%G.3
CALL :ping 192.168.%%G.4
)
GOTO :EOF
:ping
ping -n 1 %1 | find "Approximate round trip" >NUL && ECHO %1>>"%output%"
EDIT 2
Changed both solutions to use subroutine call in order to avoid premature expansion of %ip%
inside the for
loop. (Could also be fixed by enabling delayed expansion instead.)
Also quoted %output%
everywhere.