How to get and use network adapter name?

Christopher Moore picture Christopher Moore · Mar 7, 2017 · Viewed 18.3k times · Source

I am working with the following script:

@echo off
netsh interface show interface | find "Connected"
if errorlevel 1 goto #
netsh interface set interface "Local Area Connection" disabled
goto end
:#
netsh interface set interface "Local Area Connection" enabled
:end

I am trying to find a way to get the name of the found network adapters and use the name(s) instead of "Local Area Connection". The reason is that not everyone's adapters are named the same and I am trying to automate this task as much as possible.

How can I get the names of the found network adapters and use the name(s)?

Answer

Squashman picture Squashman · Mar 7, 2017

Here is a more concise way to capture the interface name.

for /F "skip=3 tokens=3*" %G in ('netsh interface show interface') do echo %%H

Putting it all together

@echo off
for /F "skip=3 tokens=1,2,3* delims= " %%G in ('netsh interface show interface') DO (
    IF "%%H"=="Disconnected" netsh interface set interface "%%J" enabled
    IF "%%H"=="Connected" netsh interface set interface "%%J" disabled
)
pause

The FOR /F command is parsing the output of the NETSH command. It is skipping the header rows. It then splits up the output into 4 meta variables.

%%G            %%H            %%I              %%J
Admin State    State          Type             Interface Name
-------------------------------------------------------------------------
Enabled        Disconnected   Dedicated        Wireless Network Connection
Enabled        Connected      Dedicated        Local Area Connection