Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables from cmd commands

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.

like image 917
Greens Avatar asked Mar 21 '26 11:03

Greens


1 Answers

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).
like image 181
DavidPostill Avatar answered Mar 25 '26 00:03

DavidPostill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!