batch-file - 检索本地连接名称并用批处理更改它
问题描述
我知道如何检索活动连接并更改本地连接名称,但我想知道如何在一个脚本中执行它们,即检索活动本地连接名称并将其更改为 LAN。
要检索当前的活动连接:
wmic.exe nic where "NetConnectionStatus=2" get NetConnectionID |more +1
将网络名称更改为:
NetSh interface set interface name="Ethernet" newname="LAN"
解决方案
您正在寻找的是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"
)
)
此处需要内部循环来避免外部将 Unicode 文本for /F
转换为 ASCII/ANSI 文本的伪影(如孤立的回车符)(另请参见我的这个答案)。wmic
for /F
我还按照用户Compo在评论中推荐wmic
的选项更改了输出格式,这样可以避免潜在的拖尾问题。/VALUE
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"
)
)
批处理文件中的%%
代表一个文字%
,a%
是where
子句中的通配符,因此上面的代码只返回Ethernet
名称中包含的项目(以不区分大小写的方式)。
为了保证 只触及一项netsh
,您可以简单地goto
在for /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
推荐阅读
- node.js - 使用云功能创建后更新 firestore 文档字段
- java - 如果我们总是把 Exception 对象放在 catch 块中,那么 finally 块就不需要了吗?
- ember.js - 升级到 Ember 3.20.2 后获取模型未定义错误
- publish-subscribe - 什么是 DCPS,它与 DDS 有什么关系?
- javascript - Socket JS 在 onload 方法中不起作用
- dolphindb - 与范围域和列表域相比,哈希域的主要应用是什么?
- spring-boot - 放心使用 Spring Boot 和 Kotlin 进行 E2E Api 测试
- python - 托盘图标在窗口启动文件夹(.pyw 扩展名)上不起作用
- google-apps-script - GAS getSharingAccess() 限制范围
- python - Python:相对导入