I want to grab only the IP addresses from the successful pings
I'm not going to try and fix the 2nd part of your batch file, it is easier to write it from scratch.
Use the following batch file (test.cmd):
@echo off setlocal setlocal enabledelayedexpansion rem throw away everything except the IPv4 address line for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "ipv4"`) do ( rem we have for example "IPv4 Address. . . . . . . . . . . : 192.168.42.78" rem split on : and get 2nd token for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do ( rem we have " 192.168.42.78" rem split on . and get 4 tokens (octets) for /f "tokens=1-4 delims=." %%c in ("%%b") do ( set _o1=%%c set _o2=%%d set _o3=%%e set _o4=%%f rem strip leading space from first octet set _3octet=!_o1:~1!.!_o2!.!_o3!. echo !_3octet! ) ) ) for /l %%i in (1,1,254) do ( rem do the ping and grab the 3rd token (ip address) if it succeeds (TTL= is found) for /f "usebackq tokens=3" %%j in (`ping -n 1 !_3octet!%%i ^| find "TTL="`) do ( rem we have ip address with a trailing : rem split on . and get the 4th token (last octet) rem we don't need the first 3 as they are already in !_3octet! for /f "tokens=4 delims=." %%k in ("%%j") do ( set _o4=%%k rem strip trailing : from last octet set _4octet=!_o4:~0,-1! echo !_4octet! ) ) ) endlocal
Notes:
The value you want is saved in
!_3octet!!_4octet!
where!_3octet! is the same as before
!_4octet! is the last octet (you don't need two extract the first 3 octets twice!)
You don't need
cd C:\Windows
One of the IP addresses will be your gateway (router) address, you probably don't want to try and run
shutdown
on the gateway!
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
- for /f - Loop command against the results of another command.
- ipconfig - Configure IP (Internet Protocol configuration)
- set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
- setlocal - Set options to control the visibility of environment variables in a batch file.
- variables - Extract part of a variable (substring).