Niclas Lindgren
Niclas Lindgren

Reputation: 562

Looping through netsh for specific interface and storing IP address to variable

I'm trying to assign the IP address of the interface Loopback to a variable but for some reason I get nothing. This works if I type it in the command shell:

C:\temp>netsh interface ip show config name="Loopback" | find  "IP Address"
IP Address:                           192.168.255.10

But when I loop through it output is empty...

set _netsh_cmd=netsh interface ip show config name="Loopback"
FOR /f "tokens=*" %%G IN ('%_netsh_cmd% ^| find "IP Address"') DO echo [%%G]

Upvotes: 0

Views: 1505

Answers (2)

Squashman
Squashman

Reputation: 14320

Works just fine without delayed exapnsion.

@echo off
set _netsh_cmd=netsh interface ip show config "Loopback"
FOR /f "delims=" %%G IN ('%_netsh_cmd% ^|find "IP Address"') DO echo [%%G]

Upvotes: 1

Bloodied
Bloodied

Reputation: 975

Found the error, you have to turn on delayedExpansion, and make the _netsh_cmd surrounded with ! rather than %. this should be correct:

setlocal enableDelayedExpansion
set _netsh_cmd=netsh interface ip show config name="Loopback"
FOR /f "tokens=*" %%G IN ('!_netsh_cmd! ^| find "IP Address:"') DO echo [%%G]

Upvotes: 1

Related Questions