Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

As part of a task that I am working on for a customer, I need to make some modifications to the enterprise logon script. Windows command-line is definitely not my area of expertise, but I am doing OK with most it. However, I have one problem that I cannot figure out how to do.

Basically, I need to get the IP address of the machines default gateway into an environment variable (for later use in the script). I know that it exists in the output of both ipconfig and of tracert, and I know how to find the exact line in their output that I need, but I cannot figure out how to get beyond that.

For example, the following command produces output like this:

>ipconfig|Find "Default Gateway"|Findstr/N "."|Findstr/B "1:"

 1:   Default Gateway . . . . . . . . . :

But now I need to somehow extract only the IP address out of this text line and then assign it to an environment variable. So, how can I do that from a Windows command-line? (Windows XP and higher).

share|improve this question
up vote 5 down vote accepted

for /f is your friend.

for /f "usebackq tokens=1,2,3 delims=:" %A in (`ipconfig ^| Find "Default Gateway" ^| Findstr/N "." ^| Findstr/B "1:"`) do @if not defined MYVAR set MYVAR=%~C

...might do the trick.

Edit: changed the code block to read the third value not the second, and needed to escape the pipes.

You could also shorten to:

for /f "usebackq tokens=1,2,3 delims=:" %A in (`ipconfig ^| Find "Default Gateway" ^| Findstr/N "."`) do @if not defined MYVAR set MYVAR=%~C, technically, the second findstr (where you limit to the first result) is actually handled by the if not defined

share|improve this answer
OK, that's completely new to me. I'll check it out ... – RBarryYoung Jan 14 '13 at 22:35
Wow, that works great. But it is coming back with some leading spaces. Is there any convenient way to trim them off? – RBarryYoung Jan 14 '13 at 22:55
Ironically, another for /f with "delims= " would do it - for /f "usebackq delims= " %A in (echo %MYVAR%) do @set MYVAR=%A – jimbobmcgee Jan 14 '13 at 22:57
Or, possibly, SET MYVAR=%MYVAR: =% (in theory, replace spaces in MYVAR with nothing -- YMMV) – jimbobmcgee Jan 14 '13 at 22:58
Ever notice that hardly anyone uses For/if and environment variables anymore ? Tons of expert advice across the web from people insisting you type out hard paths "c:\program files" and just change it for your system instead of just %programfiles% or others. Jim, are you and old hand or just learned from old wizards ? I detect experience in your Fu – user154407 Jan 14 '13 at 23:02

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.