【问题标题】:Retrieve local area connection name and change it with batch检索本地连接名称并用批处理更改它
【发布时间】:2019-06-26 13:14:44
【问题描述】:

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

检索当前活动连接:

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

将网络名称更改为:

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

【问题讨论】:

    标签: batch-file


    【解决方案1】:

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

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

    这里需要内部for /F 循环,以避免外部for /Fwmic 的Unicode 文本转换为ASCII/ANSI 文本时产生伪影(如孤立的回车字符)(另请参阅@987654323 @我的)。

    我还按照用户Compocomment 中的建议,通过/VALUE 选项更改了wmic 的输出格式,从而避免了潜在的尾随SPACEs 带来的麻烦。


    请注意,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"
        )
    )
    

    批处理文件中的%% 代表一个文字%%where 子句中的通配符,因此上述代码仅返回名称中带有Ethernet 的项目(在某种情况下) - 不敏感的方式)。


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

    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 class

    【讨论】:

    • 请注意,使用 WMIC 的默认表格格式可能会在返回的字符串末尾附加一个或多个空格。这意味着您将有效地传递name="Local Area Connection  ",结果可能会失败。因此,我建议@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"…您也可以将/Format:List 替换为/Value
    • 谢谢,@Compo,你说得对,我完全忘记了尾随的 空格;查看我编辑的答案...
    猜你喜欢
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多