Christopher Moore
Christopher Moore

Reputation: 59

How to get and use network adapter name?

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)?

Upvotes: 1

Views: 29164

Answers (2)

Squashman
Squashman

Reputation: 14320

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

Upvotes: 4

abelenky
abelenky

Reputation: 64730

for /F "tokens=4*" %%a in ('netsh interface show interface ^| more +2') do echo %%a %%b

Upvotes: 2

Related Questions