command line to determine which Ethernet interface is in use

user1858210 picture user1858210 · Nov 28, 2012 · Viewed 7.2k times · Source

I have a script that I wrote to help to configure computers after they are deployed. The script does things like sets computer name, enable's BitLocker, etc. The one thing that I am struggling with is the setting of an IP address. The computers that I am using (servers to be specific) have 4 NIC ports and they are named Local area connection and Local area connection 2-4. The problem is that the technicians that deploy these servers don't always plug into the same port, and additionally the deployment image doesn't always assign the ethernet net local area connection to the NIC port 1.

Here is a copy of the script that I have, which works perfectly if only a single NIC port is enabled. What I need to do is pipe the output of the Local Area Connection name that has an IP address (because DHCP already exists) into a variable that I can put into my netsh command.

Current code in place

:IPADDRESS
@echo Would you like static or DHCP?
@echo press 1 for static
@echo press 2 for dhcp
Choice /C:12 /N /M "?:"
IF ERRORLEVEL 2 GOTO IPDHCP
IF ERRORLEVEL 1 GOTO IPSTATIC

:IPSTATIC
set /P _IPADDR=Please enter IP address:
set /p _Subnet=Please enter Subnet:
set /p _DefaultGateway=Please Enter Default Gateway:

netsh interface ip set address name="Local Area Connection 2" static %_IPADDR% %_Subnet% %_DefaultGateway%
goto START

:IPDHCP
  netsh interface ip set address "Local Area Connection 2" dhcp
 goto START

 :disipaddr
  netsh interface ip show config name="Local Area Connection 2"

The name "Local Area Connection 2" is the part that changes from build to build. So that is the part that I need to isolate. I am fairly certain that the for /p and using it against either ipconfig /all or netsh interface ip show config would be the correct way to go.

Thank you in advance for all of the help.

Answer

Benyamin Jafari picture Benyamin Jafari · Feb 4, 2015

This will work and tested on Windows 7.

A batch.bat file:

@echo off

for /f "tokens=2 delims==" %%F in ('wmic nic where "NetConnectionStatus=2 and AdapterTypeId=0" get  NetConnectionID /format:list') do set interfaceName=%%F

echo Your Interface is %interfaceName%

pause