1

I know how to retrieve the active connection and change a local area connection name but I would like to know how to do them in one script, i.e. retrieve the active Local area connection name and change it to LAN.

To retrieve current active connections:

wmic.exe nic where "NetConnectionStatus=2" get NetConnectionID |more +1 

Change network name to:

NetSh interface set interface name="Ethernet" newname="LAN"
Compo
  • 36,585
  • 5
  • 27
  • 39

1 Answers1

3

What you are looking for is the for /F loop, which is capable of capturing the output of a command:

for /F "tokens=1* delims==" %%J in ('
    wmic NIC where "NetConnectionStatus=2" get NetConnectionID /VALUE
') do (
    for /F "delims=" %%I in ("%%K") do (
        netsh interface set interface name="%%I" newname="LAN"
    )
)

The inner for /F loop here is needed to avoid artefacts (like orphaned carriage-return characters) from the conversion of wmic's Unicode text to ASCII/ANSI text by the outer for /F (see also this answer of mine).

I also changed the output format of wmic by the /VALUE option as recommended by user Compo in a comment, which avoids trouble with potential trailing SPACEs.


Note that the wmic query might return more than one adapter, so perhaps you want to extend the where clause to avoid that, like this, for example:

for /F "tokens=1* delims==" %%J in ('
    wmic NIC where "NetConnectionStatus=2 and NetConnectionID like '%%Ethernet%%'" get NetConnectionID /VALUE
') do (
    for /F "delims=" %%I in ("%%K") do (
        netsh interface set interface name="%%I" newname="LAN"
    )
)

The %% in the batch file represents one literal %, and a % is a wildcard in where clauses, so the above code only returns items with Ethernet in their names (in a case-insensitive manner).


To guarantee that only one item is touched by netsh, you could simply use goto in the for /F loops to break them:

for /F "tokens=1* delims==" %%J in ('
    wmic NIC where "NetConnectionStatus=2" get NetConnectionID /VALUE
') do (
    for /F "delims=" %%I in ("%%K") do (
        netsh interface set interface name="%%I" newname="LAN"
        goto :NEXT
    )
)
:NEXT

Reference: Win32_NetworkAdapter class

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • 1
    Just to note that using WMIC's default tabular format would likely append one or more spaces to the end of the returned string. This would mean that you would effectively be passing `name="Local Area Connection  "`, which may as a result fail. I would suggest therefore `@For /F "Tokens=1*Delims==" %%A In ('WMIC NIC Where "NetConnectionStatus='2'" Get NetConnectionID /Format:List 2^>NUL')Do @For /F "Tokens=*" %%C In ("%%B")Do @NetSH Interface Set interface name="%%C"…`. *You could also replace `/Format:List` with `/Value`.* – Compo Jun 26 '19 at 16:07
  • Thanks, @Compo, you're absolutely right, I totally forgot about the trailing _spaces_; see my edited answer... – aschipfl Jun 26 '19 at 16:19