batch-fileipv4setx

Windows 7 batch - get last octet of IPv4 address and set environment variable


I have Windows 7 machines that get imaged, and after imaging I have to set the environment variable STATION to the last octet of the machine's IP address. How would I parse the IP address and grab the last octet to set the STATION variable?

This only sets the variable to the full ip address:

@echo off
for /f "tokens=1 delims=:" %%j in ('ping %computername% -4 -n 1 ^| findstr Reply') do (set localip=%%j)
SETX /m STATION "%localip:~11%"

Solution

  • do it with another for:

    for /f "Tokens=4 delims=." %%a in (%localip%) do set lastOctett=%%a
    

    May I suggest:

    for /f "tokens=2 delims=[]" %%a in ('ping %computername% -4 -n 1') do for /f "tokens=4 delims=." %%b in ("%%a") do SETX /m STATION %%b
    

    (I used a different method to get the IP, because yours depends on local settings - for example on my computer I would have to search for Antwort instead of Reply. But the syntax is the same in all languages, so the IP is always enclosed by [ and ])