How to retrieve Ethernet adapter name in Windows 8.1 batch script

喜你入骨 提交于 2020-01-06 14:10:50

问题


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!


回答1:


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%



回答2:


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

netsh interface ip set address name=%interface% static 192.168.1.10 255.255.255.0 192.168.1.1



回答3:


Why not use the following, then use this post to select the correct interface.

C:\Scripts>netsh interface show interface
Admin State    State          Type             Interface Name
-------------------------------------------------------------------------
Enabled        Connected      Dedicated        Local Area Connection


来源:https://stackoverflow.com/questions/29523583/how-to-retrieve-ethernet-adapter-name-in-windows-8-1-batch-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!