3

I'm trying to make a batch program that fetches variables from base CMD commands. For example:

c:\Users> ipconfig
.....
IPv4 Address ....... 123.456.7.89
.....

Say I wanted to make a batch program that prints only the IP address on the screen such as:

@echo off
echo (IP Address Variable Here)
pause;

What would I need to do?

Appreciate your time.

1 Answer 1

3

I wanted to make a batch program that prints only the IP address on the screen

Use the following batch file.

GetIPAddress.cmd:

@echo off
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"
    set _ip=%%b
    rem strip leading space
    set _ip=!_ip:~1!
    )
  )
echo %_ip%
endlocal

Notes:

  • The value you want is saved in _ip

Example usage and output:

F:\test>ipconfig | findstr /i "ipv4"
   IPv4 Address. . . . . . . . . . . : 192.168.42.78

F:\test>GetIPAddress
192.168.42.78

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).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.