Ariel Tosi
Ariel Tosi

Reputation: 11

create a batch file to get a ip address from a network interface name

I have servers with more than 2 network interfaces. ie. Primary.nic, BEN.nic, HB.nic etc

Using the following lines I'm getting the IP from the last NIC:

for /f "tokens=2 delims=:" %%a in ('ipconfig ^| find "IP" ^| find "Address" ^| find /v "v6"') do (
    set IPAddr=%%a
)
echo=%IPAddr%

I need to find the IP address from a specific NIC name ie. "BEN"

I've tried this too:

@echo on
setlocal ENABLEEXTENSIONS

setlocal EnableDelayedExpansion
set result=false
for /f "tokens=2 delims=:" %%a in ('ipconfig ^| "BEN.NIC" ^| find "IP Address"') do (
    set IPAddr=%%a
)
echo %IPAddr%

It doesn't work.

Upvotes: 1

Views: 2731

Answers (1)

JosefZ
JosefZ

Reputation: 30103

Next script should work:

@ECHO OFF >NUL
SETLOCAL enableextensions disabledelayedexpansion
set "nicFunName=wiredEthernet"
for /F "usebackq tokens=*" %%G in (
  `wmic nic where "NetConnectionID='%nicFunName%'" get index /value^|find "="`) do (
    rem echo G %%G
    for /F "tokens=*" %%H in ("%%G") do (
        rem echo H %%H
        for /F "usebackq tokens=2 delims==" %%I in (
            `wmic NICCONFIG where %%H get IPAddress /value`
        ) do (
            rem echo I %%I
            for /F "tokens=1,2 delims={,}" %%J in ("%%I") do (
                echo IPv4=%%J IPv6=%%K
                rem or without double quotes: echo IPv4=%%~J IPv6=%%~K
            ) 
        )
    )   
)
ENDLOCAL
goto :eof

Where the for loops are

  • %%G to retrieve the NIC index in Index=0 format applicable as next wmic query where clause condition
  • %%H to remove a superabundand and harmful carriage return (0x0D) from wmic output
  • %%I to retrieve the IPAddress by index in {"<ipv4>","<ipv6>"} format
  • %%J to split previous output

You could add a most outer loop as follows:

for %%m in (
    "Primary.nic" "BEN.nic" "HB.nic"
) do (
      rem all for... code here  with 
      rem                                where "NetConnectionID='%%~m'"
      rem or call a subroutine or call a batch etc.
)

Upvotes: 1

Related Questions