首页 > 解决方案 > 检索本地连接名称并用批处理更改它

问题描述

我知道如何检索活动连接并更改本地连接名称,但我想知道如何在一个脚本中执行它们,即检索活动本地连接名称并将其更改为 LAN。

要检索当前的活动连接:

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

将网络名称更改为:

NetSh interface set interface name="Ethernet" newname="LAN"

标签: batch-file

解决方案


您正在寻找的是for /Floop,它能够捕获命令的输出:

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

此处需要内部循环来避免外部将 Unicode 文本for /F转换为 ASCII/ANSI 文本的伪影(如孤立的回车符)(另请参见我的这个答案)。wmicfor /F

我还按照用户Compo评论中推荐wmic的选项更改了输出格式,这样可以避免潜在的拖尾问题。/VALUESPACEs


请注意,wmic查询可能返回多个适配器,因此您可能希望扩展where子句以避免这种情况,例如:

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

批处理文件中的%%代表一个文字%,a%where子句中的通配符,因此上面的代码只返回Ethernet名称中包含的项目(以不区分大小写的方式)。


为了保证 只触及一项netsh,您可以简单地gotofor /F循环中使用来打破它们:

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

参考:Win32_NetworkAdapter 类


推荐阅读