将 netconnectionid 批量传递给 netsh 接口命令



>我正在尝试编写一个批处理脚本,该脚本将从wmin nic获取netconnectionid,然后将每个返回的值传递到netsh命令中,该命令将告诉接口从DHCP获取其IP。

这是我到目前为止所拥有的(非操作)

@echo Off
For /f "tokens=2" %%a In ('wmic nic where "netconnectionid like '%%'" get netconnectionid /value') Do (
    Call :dhcp "%%a %%b"
)
pause
exit
:dhcp
netsh interface ip set address %%b dhcp

需要该脚本而不是运行"本地连接"或"无线网络连接"命令的原因是,此脚本将在netconnectionid不再遵循标准的计算机上运行。

作为批处理新手,我在破译循环以及到底哪里出了问题时遇到了问题。

你非常接近。最重要的是,您需要指定用于解析字符串的分隔符。由于该 wmic 命令将返回类似"NetConnectionId=Local Connection"之类的字符串,因此您需要指示要在=处拆分字符串,而不是像通常那样拆分空格。

第二件事是,当你调用一个函数时,你可以访问传递给它的参数,第一个参数%1,第二个参数%2,等等。

@echo off
:: tokens=2 indicates that of all the tokens that would normally be returned, we only want the second one
:: delims== indicates that the string should be split up wherever there is an = symbol
for /f "tokens=2 delims==" %%A in ('wmic nic where "netconnectionid like '%%'" get netconnectionid /value') do (
    call :dhcp "%%A"
)
pause
exit /b
:dhcp
:: %~1 refers to the first parameter passed into the function, but without the quotation marks
netsh interface set address %1 dhcp

最新更新