Search code examples
batch-filenetwork-programmingwindows-8.1static-ip-address

How to retrieve Ethernet adapter name in Windows 8.1 batch script


I'm looking to pull the Ethernet adapter name out of ipconfig to use in a batch script which will create a static ip to that adapter name using netsh.

Ethernet adapter Ethernet0:
    Connection-specific DNS Suffix  . : foo.bar.com
    IPv4 Address. . . . . . . . . . . : 10.0.0.123
    Subnet Mask . . . . . . . . . . . : 255.255.255.0
    Default Gateway . . . . . . . . . : 10.0.0.456

What I am trying to do is pull out Ethernet0 and use that in the following netsh command (net_city and net_lab are inputted by the user).

netsh interface ip set address "<adapter name>" static 10.%net_city%.15%net_lab%.235 255.255.255.0 10.%net_city%.15%net_lab%.1 1

What would be the best way to retrieve the name? I have begun looking into regex to try and filter out the name.

Thank you!


Solution

  • As already suggested, you can use netsh to gather a list of interfaces, and then get the user to select one using choice. Here is my implementation of that:

    @echo off
    setLocal enableDelayedExpansion
    set c=0
    set "choices="
    
    echo Interfaces -
    
    for /f "skip=2 tokens=3*" %%A in ('netsh interface show interface') do (
        set /a c+=1
        set int!c!=%%B
        set choices=!choices!!c!
        echo [!c!] %%B
    )
    
    choice /c !choices! /m "Select Interface: " /n
    
    set interface=!int%errorlevel%!
    echo %interface%
    

    The choice command changes the value of errorlevel, and by making the name of each variable comprising your list of interfaces int1, int2, etc. you can simply call them with !int%errorlevel%! after the choice command.

    If you can assume there will only ever be one interface, then you can simply do the following.

    for /f "skip=2 tokens=3*" %%A in ('netsh interface show interface') do set interface=%%B
    
    echo %interface%