1

I'm currently having a hard time figuring out how to get the active interface names as a variable output which can be later on used in the code. I've been reading here a bit, how to use the cmd output as a variable, but I need the specific names which are active.

My current code:

    @echo off

    netsh interface show interface


    FOR /F "tokens=* USEBACKQ" %%F IN (`netsh interface show interface`) DO (
    SET var=%%F
    )
    ECHO %var%
    Pause

Which displays this image: enter image description here We can see that due to

netsh interface show interface

, two connected interfaces and two non connected are shown. However, how do i get f.ex. Ethernet 2 and WiFi as a variable only like %%V ?

Advena
  • 1,664
  • 2
  • 24
  • 45
  • 2
    `FOR /F "skip=2 tokens=3,*" %%A IN ('netsh interface show interface') DO echo %%B` – Stephan Sep 12 '17 at 15:29
  • Read the documentation for the `for` command - `for /?|more` from the prompt, or look through SO for thousands of examples of how to use `for`. – Magoo Sep 12 '17 at 15:30
  • @Stephan, this very useful, but shows now all 4 of them, where I only need the active ones. – Advena Sep 12 '17 at 15:36
  • 1
    So `Ethernet 2` is connected? At the screenshot it looks very much like `Disconnected`... Please be precise if you want precise answers. – Stephan Sep 12 '17 at 15:42
  • @Stephan, no. What I need as a result from this example is to get WiFi and Virtual Box as variable. – Advena Sep 12 '17 at 15:44

2 Answers2

1

to get the names of all interfaces that are connected:

FOR /F "tokens=3,*" %%A IN ('netsh interface show interface^|find "Connected"') DO echo %%B

Note: this is language dependent.

For a language independent solution use wmic (which has it's own traps and oddities):

for /f "tokens=2 delims==" %%a in ('wmic nic where (NetConnectionStatus^=2^) get name /value') do (
  for /f "delims=" %%b in ("%%a") do echo %%b
)

The inner for is to handle the ugly wmic line endings

Stephan
  • 53,940
  • 10
  • 58
  • 91
0

Because the output of WMIC has the 'ugly' <CR><CR><LF> line endings and the value of NetConnectionID will often have unwanted trailing spaces, I'd suggest something more like this to retrieve only connected network adapters as variables:

@Echo Off
Set "i=0"
For /F "Skip=1Delims=" %%A In (
 'WMIC NIC Where "NetConnectionStatus=2" Get NetConnectionID'
) Do For /F "Delims=" %%B In ("%%A") Do Call :Sub %%B
Set NIC[
Timeout -1
Exit/B
    :Sub
    Set/A i+=1
    Set "NIC[%i%]=%*"
Compo
  • 36,585
  • 5
  • 27
  • 39