Pass netconnectionid to a netsh interface command in batch

766 views Asked by At

I'm trying to write a batch script that will fetch the netconnectionid from wmin nic and then pass each of the returned values into a netsh command that will tell the interface to get it's IP from DHCP.

Here's what I have so far (non-operational)

@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

The reason the script is needed instead of running commands for "Local Area Connection" or "Wireless Network Connection" is that this script will be ran on machines where the netconnectionid is no longer following the standard.

Being new to batch, I'm having issues deciphering the loop, and where exactly it's going wrong.

1

There are 1 answers

6
SomethingDark On BEST ANSWER

You were very close. The biggest thing is that you needed to specify the delimiter to use to parse the string. Since that wmic command will returns strings like "NetConnectionId=Local Area Connection", you need to indicate that you want to split the string at the = instead of the spaces like it ordinarily would be.

The second thing is that when you call a function, you can access the parameters that are passed into it with %1 for the first parameter, %2 for the second parameter, etc.

@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