4

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 . . . . . . . . . : 199.99.9.1

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).

1 Answer 1

6

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

...as, technically, the second findstr (where you limit to the first result) is actually handled by the if not defined

8
  • OK, that's completely new to me. I'll check it out ... Jan 14, 2013 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? Jan 14, 2013 at 22:55
  • Ironically, another for /f with "delims= " would do it - for /f "usebackq delims= " %A in (echo %MYVAR%) do @set MYVAR=%A Jan 14, 2013 at 22:57
  • 1
    Or, possibly, SET MYVAR=%MYVAR: =% (in theory, replace spaces in MYVAR with nothing -- YMMV) Jan 14, 2013 at 22:58
  • 1
    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, 2013 at 23:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .