Misc, References, Resources, Scripting, Windows
comments 2

Finding Network Adapter with an active link

Recently, I wrote a small batch script to configure a bunch of systems with similar settings. In this process, I had to find out a NIC with an active connection to assign it an IP address. However, I could not find a straight forward way to do that in a batch script. I started looking at WMIC for some help and found that the following command could be of some help

WMIC NIC where “NetConnectionStatus=’2′ and NetConnectionID=’Local Area Connection'” GET NetConnectionID /VALUE’

This command would resturn something like NetConnectionID=Local Area Connection. This isn’t really helpful considering the fact that we will not be able to use the complete string anywhere in our script. We need only the Local Area Connection part of the string. The workaround was to place this command in a FOR statement and retrieve the required value. Here is how I did that

FOR /F “tokens=2 delims==,” %%i in (‘WMIC NIC where “NetConnectionStatus=’2′ and NetConnectionID=’Local Area Connection'” GET NetConnectionID /VALUE’) DO @set Connect1=%%i

In the above command, NetConnectionStatus=’2′ is used to find if the given network connection has an active link or not. If Local Area Connection has an active link, the result of this overall command will be setting a DOS environment variable %Connect1% to ‘Local Area Connection’

In the subsequent sections of the script, you can simply check if the variable is set or not and then use the same value in the script

Filed under: Misc, References, Resources, Scripting, Windows

by

Ravikanth is a principal engineer and the lead architect for Microsoft and VMware virtualized and hybrid cloud solutions within the Infrastructure Solutions Group at Dell EMC. He is a multi-year recipient of Microsoft Most Valuable Professional (MVP) award in Windows PowerShell (CDM) and Microsoft Azure. Ravikanth is the author of Windows PowerShell Desired State Configuration Revealed (Apress) and leads Bangalore PowerShell and Bangalore IT Pro user groups. He can be seen speaking regularly at local user group events and conferences in India and abroad.