Hey, Scripting Guy!Sure, We're Adaptable

The Microsoft Scripting Guys

This column is based on a prerelease version of Windows Vista. Some information herein is subject to change.

Download the code for this article: ScriptingGuys2006_11.exe (151KB)

YOU'VE PROBABLY heard that one of the best ways to advance your career is to network-you know, make connections with other people in the industry so you can learn from them, share information with them, and possibly get a new job from them. The Scripting Guys never really got the hang of that whole career networking thing (which should be obvious), but we do know a thing or two about computer networking. That's because you can do a lot with networking through scripts.

Windows® Management Instrumentation (WMI) provides a number of classes you can use in order to both control and monitor your network environment. Two of those classes, Win32_NetworkAdapter and Win32_NetworkAdapaterConfiguration, allow you to work with-what else?-network adapters on your computers.

A question we hear frequently is "How do I enable and disable my network adapters through a script?" Well, we won't hold you in suspense. We'll tell you right now that you can't. At least not until you're running Windows Vista™. In Windows Vista two new methods have been added to the Win32_NetworkAdapter class: Enable and Disable. We'll take a look at these methods in a minute. But first, before you get too dejected, we'll show you some of the things you can do with pre-Windows Vista operating systems. Just for starters, you can find out what network adapters are actually available on the machine (see Figure 1). That's good stuff, right?

Figure 1 Finding Network Adapters

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter")

For Each objItem in colItems 
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo
Next

In Figure 1, we start by connecting to the WMI service on the local computer. Sure, it's easy enough to find the network adapters on your local computer through the GUI, but try using the GUI to get information about the network adapters on a remote computer. That's one of the beauties of this script, and of WMI scripting in general: you can run this same script against a remote computer simply by changing the value of strComputer to the name of the remote computer.

After we've connected to the WMI service we then query for the Win32_NetworkAdapter class. This query returns a collection of all the network adapters on the computer. From there all we have to do is set up a For Each loop to walk through the collection of adapters and echo back the Name and Description of each one. Your output will look something like this:

Name: Broadcom NetXtreme 57xx Gigabit Controller
Description: Broadcom NetXtreme 57xx Gigabit Controller

Name: RAS Async Adapter
Description: RAS Async Adapter

Name: WAN Miniport (L2TP)
Description: WAN Miniport (L2TP)

Name: WAN Miniport (PPTP)
Description: WAN Miniport (PPTP)

There's a lot more information you can retrieve about your network adapters just by echoing back different properties of Win32_NetworkAdapter, such as DeviceID, Manufacturer, and TimeOfLastReset. For more information, see the magnum opus "Automating TCP/IP Networking on Clients", found-where else?—in the Script Center.

Adapting to Change

With the Win32_NetworkAdapter class all you can do is retrieve information about network adapters. If you want to actually change any of the adapter settings you need to use the Win32_NetworkAdapterConfiguration class. Not only does this class provide additional information about your adapters (thanks to properties not found in Win32_NetworkAdapter), but it also offers several methods that allow you to configure your network adapters to your liking.

For example, maybe you can't enable and disable the adapters, but you can enable and disable dynamic host configuration protocol (DHCP) on each TCP/IP-enabled adapter. Figure 2 shows a script that looks for all TCP/IP-enabled adapters, checks to see whether DHCP is enabled on each adapter and, if it isn't, enables it.

Figure 2 Enabling DHCP

strComputer = "." 
Set objWMIService = GetObject _
    ("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapterConfiguration Where IPEnabled = 'True'")

For Each objItem in colItems
    If objItem.DHCPEnabled = False Then
        Wscript.Echo objItem.Caption
        intReturn = objItem.EnableDHCP
        Select Case intReturn
            Case 0
                Wscript.Echo "DHCP enabled"
            Case 1
                Wscript.Echo "You must reboot before DHCP will be enabled"
            Case Else
                Wscript.Echo "Error occurred"
        End Select
        Wscript.Echo
    End If
Next

Just like the script in Figure 1, the script in Figure 2 connects to the WMI service on the local computer. It then queries for the Win32_NetworkAdapterConfiguration class. Note that because we're concerned only with those adapters that are TCP/IP-enabled we included a Where clause in our query:

Where IPEnabled = 'True'

This clause specifies that we want only the instances of the Win32_NetworkAdapterConfiguration class where the IPEnabled property is True, meaning the adapter associated with that instance is TCP/IP-enabled.

Next, we use a For Each loop to iterate through the collection of adapters returned from our query. Within the loop we first check the DHCPEnabled property of each adapter. If the property is set to False it means that DHCP is not enabled, so we want to enable it. We do that by calling the EnableDHCP method on the adapter object. That's really all there is to it.

Just to make it easier to see what's happening in the script, we echoed back the Caption property so we know which adapters we're working with. We also included a Select Case statement and created descriptors of each possible result for the end user. The EnableDHCP method returns an integer value when it's finished. A value of 0 means the method ran successfully and DHCP is enabled. A value of 1 means the method ran successfully but the computer needs to be restarted for the change to take effect. Any other value means something went wrong and DHCP was not enabled. We use the Select Case statement to check these integer values and return an appropriate message.

You can also disable DHCP; this is done by setting a static IP address and a subnet mask on the adapter (see Figure 3).

Figure 3 Setting an IP Address

arrIPAddress = Array("192.168.0.12")
arrSubnetMask = Array("255.255.255.0")

strComputer = "." 
Set objWMIService = GetObject _
    ("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapterConfiguration Where IPEnabled = 'True'")

For Each objItem in colItems
    If objItem.DHCPEnabled = True Then
        Wscript.Echo objItem.Caption
        intReturn = objItem.EnableStatic(arrIPAddress, arrSubnetMask)
        Select Case intReturn
            Case 0
                Wscript.Echo "Static address assigned"
            Case 1
                Wscript.Echo "You must reboot before the static address will take effect"
            Case Else
                Wscript.Echo "Error occurred"
        End Select
        Wscript.Echo
    End If
Next

The script in Figure 3 is almost identical to the script in Figure 2, with just a few key differences. At the beginning of the script we declare two arrays, arrIPAddress and arrSubnetMask, and assign a value to each. Then in our For Each loop, rather than checking to see if DHCPEnabled is False, we check to see if it's True, meaning DHCP is enabled (in turn, meaning that we want to disable it). We then call the EnableStatic method on the adapter object. You'll notice that, unlike the EnableDHCP method, EnableStatic takes parameters. These parameters are the arrays we declared earlier that contain the new static IP address and the subnet mask.

Windows Vista Additions

As promised (because Scripting Guys never-or at least rarely-break their promises), we'll now show you what you can do in Windows Vista. As we said earlier, in Windows Vista the WMI class Win32_NetworkAdapter has two new methods, Enable and Disable, that allow you to enable and disable your network adapters. There's also a new property, NetEnabled, that returns True if the adapter is enabled and False if it isn't. Figure 4 shows a script that finds all the network adapters on the computer that are disabled, and then enables them.

Figure 4 Enabling Network Adapters

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapter Where NetEnabled = 'False'")

For Each objItem in colItems 
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "Description: " & objItem.Description
    objItem.Enable
    Wscript.Echo
Next

This is almost identical to the script we showed you in Figure 1. (In case you hadn't noticed, we're strong advocates of reuse.) We connect to the WMI service on the local computer and query for all instances of Win32_NetworkAdapter. Because we're interested in only the adapters that are disabled, we added a Where clause:

Where NetEnabled = 'False'

This clause uses the new NetEnabled property to specify that only adapters in which NetEnabled is set to False—in other words, where the network adapter is disabled—should be returned from the query. We then, once again, set up a For Each loop to loop through the collection of network adapter objects returned from the query. After echoing back the Name and Description of the adapter, we call the Enable method to enable the adapter.

It's all pretty simple, right? Now if only we could get the hang of this other type of networking.

The Microsoft Scripting GuysThe Scripting Guys work for—well, are employed by—Microsoft. When not playing/coaching/watching baseball (and various other activities) they run the TechNet Script Center. Check it out at www.scriptingguys.com.

© 2008 Microsoft Corporation and CMP Media, LLC. All rights reserved; reproduction in part or in whole without permission is prohibited.