@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 a command that only runs if the previous command (the first before && ) completed successfully (technically speaking, returned exit code 0 ).
There is a similar approach for the opposite case. If you want to perform some actions on the unsuccessful result of the command, you put || after it, and then the team that implements your action.
EDIT
One note on ping . Sometimes you get a notification from the router that the host is unreachable. In this case, ping still exits with code 0 ("successful"), because it receives a response, even if it is from the router and not from the actual host.
If this can happen to your hosts, and you do not want to have such false positives in the output file, you will have to analyze the ping output for some keywords indicating whether pinging was successful, while you can rely on lines showing aggregate statistics: they appear only if the response was from the intended host.
So here is an 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
Both solutions have been changed for using a subroutine call to avoid premature expansion of %ip% inside a for loop. (It can also be fixed by enabling slow expansion.)
Also cited is %output% everywhere.
source share