Automating TCP/IP Networking on Clients With MSH

Scripting Basic TCP/IP Networking on Clients with MSH

A re-write of Microsoft's The Scripting Guys Column on Microsoft's TechNet Site.
The intention was to show how WMI and Monad Fit Together)
See:
http://www.microsoft.com/technet/scriptcenter/topics/networking/02_atnc_basic.mspx) for the original column

NB: This is a work in progress. It's around half complete.


In just about all sorts of IT environments, network administrators need to change network client information. In transient environments such such as convention centres, hotels, and universities, this information is changed frequently because transient users and computers come and go. In suchcomputing environments, you can use scripts to configure network clients, which may be very useful. And on less dynamic TCP/IP networks, scripting basic configuration on clients can help standardize change and configuration management, avoid manual administrative errors, and accomplish bulk changes on many clients rapidly and effectively.

Windows provides extensive GUI and command-line functionality to help network administrators manage TCP/IP network clients. Through Network and Dial-Up Connections in Windows XP and Windows Server 2003, you can view and modify most network settings. Widely used command-line tools such as Ipconfig.exe, NSLookup.exe, Ping.exe, and Tracert.exe provide additional tools. Sometimes these are all you need to accomplish a networking task. However, if you find yourself clicking OK repeatedly or trying to change a parameter that is contingent on the state of two other parameters on a hundred computers, the techniques detailed in this paper should prove useful.

This section covers the basic techniques for retrieving the most common TCP/IP settings, such as IP addresses and subnet masks. The section begins with a brief review of the non-scripting methods and command-line methods that you can use to perform these tasks. Next, the section covers a variety of scripting techniques for working with the two most important WMI classes for these tasks. Finally, it shows how to retrieve extended TCP/IP settings by using a script that reproduces nearly all the functionality of the ipconfig /all command.

Retrieving Basic TCP/IP Client Settings by Using Non-Scripting Methods

To simply check a couple of TCP/IP settings on one computer, many network administrators prefer to use the Windows interface that is provided in Windows through Network Connections.

To check TCP/IP settings by using the Windows interface in Windows

  1. Open Control Panel and double-click Network Connections.
  2. In the Network Connections dialog box, right-click a specific network connection and then click Properties.
  3. In the properties dialog box for the network connection, select Internet Protocol (TCP/IP) and then click Properties.

Figure 1 shows the available options when you use the Internet Protocol (TCP/IP) Properties dialog box.Figure 1   Internet Protocol (TCP/IP) Properties Dialog Box

 


Figure 2   Typical Network Settings Displayed by Ipconfig.exe

Figure 2   Typical Network Settings Displayed by Ipconfig.exe
See full-sized image

You can use Ipconfig.exe not only to display networking settings but also to perform certain operations on a network adapter. For example, the /renew option renews DHCP leases and the /flushdns option purges the DNS client resolver cache.

Retrieving Basic Settings with a Script

By writing scripts in MSH, system administrators can create more powerful and flexible tools to manage a broader range of Windows functionality.

For each setting in the Advanced TCP/IP Settings dialog box, WMI classes offer properties and methods that can retrieve and modify client network settings, the most important of which is the Win32_NetworkAdapterConfiguration class. Figure 3 illustrates which WMI classes correspond to different elements of the Advanced TCP/IP Settings dialog box.

Figure 3   How TCP/IP WMI Properties and Methods Correspond to the Windows UI

Figure 3   How TCP/IP WMI Properties and Methods Correspond to the Windows UI
See full-sized image

For purposes of scripting, a WMI class is simply a way of packaging a related set of configuration settings and returning them to your script to manipulate. Your script can use properties to retrieve the settings and methods in order to change them. The Win32_NetworkAdapterConfiguration class includes properties and methods that correspond to the DNS, WMI, and Options tabs of the Advanced TCP/IP Settings dialog box. The sections that follow cover this in detail.

Using the Win32_NetworkAdapterConfiguration WMI Class

The 61 properties and 41 methods of Win32_NetworkAdapterConfiguration cover nearly all the settings and actions that are available through the Windows interface or command-line tools, and some that are not. To retrieve a property or call a method, only a few lines of MSH code are required, as the following examples illustrate. For more information about the properties and methods for this WMI class, see the WMI Software Development Kit (SDK) topic at http://go.microsoft.com/fwlink/?LinkId=29991.

To get any WMI object, you call Get-WMIObject with the name of the WMI class to return. This returns a collection containing zero or more object instances of the type requested. Each instance contains properties and methods. The objects, properties, and methods are documented in detail in the WMI Reference of the WMI SDK under "Scripting API for WMI."

Displaying One Setting

The following example displays the DHCPEnabled property of Win32_NetworkAdapterConfiguration. The DHCPEnabled property returns a Boolean value, which is a way of representing a condition that can be either true or false.

The pattern used in this simple script can be repeated for any property of Win32_NetworkAdapterConfiguration even those that return arrays. Handling properties that return arrays is discussed later in this paper.

Scripting Steps

1.Get a collection of all the instances of the Win32_NetworkAdapterConfiguration class using Get-WMIObject. This returns an array of  network adapter configuration objects on the computer.
2.For each network adapter configuration in the array, display the Boolean property corresponding to the DHCP Enabled setting in the IP addresses box on the IP Settings tab of the Advanced TCP/IP Settings dialog box. Display this list using the built-in Format-Table Cmdlet, and use the -auto setting.

Listing 1  OneSetting.msh

1   
2
3
  
#OneSetting.msh
$netadapters = Get-WMIObject Win32_NetworkAdapterConfiguration
$netadapters | Format-Table DHCPEnabled -auto

When you run these commands, output similar to the following is displayed in the MSH.EXE command window:


DHCPEnabled
-----------
True
True
False
False
False
False
False
False
False
False
False
False
True


[C:\]:

 

Note: Even though a computer that contains only one physical network interface card, WMI may return settings for multiple network adapters. This is because some kinds of network connections, such as virtual private networks (VPNs), create their own virtual network adapters.

Displaying a Setting for Specific Network Adapters

The previous example displays the value of the DHCPEnabled property for every network adapter configuration that WMI finds. Sometimes you may not want to work with all network adapters. For example, certain features, such as Routing and Remote Access and virtual private networks, can create their own virtual network adapter configurations on which TCP/IP is not enabled.

To filter for IP-enabled network adapters only, you can use the Where-object cmdlet to filter the objects returned from WMI.  The most basic is of the form Get-WMIObject "classname". This query returns all instances of the WMI class. Thus Get-WMIObject Win32_Service would return an array of objects, one per service each of the services currently running on the computer. You can also use the -computer switch on Get-WMIObject to change the computer being queried.

The following script uses the Where-Object Cmdlet to filter the results returned from Get-WMIObject. The script uses Where-Object {$_.IPEnabled} to filter those instances of the Win32_NetworkAdapterConfiguration class where the Boolean value of its IPEnabled property is True, in other words, for which IP is enabled.

This example also displays a second property, Index (see line 5), to distinguish between adapters when more than one is installed. Index is the key property for the Win32_NetworkAdapterConfiguration class, serving as the unique identifier for each instance of the class. The value of Index is an integer, starting with 0 for the first active network adapter configuration and incrementing by 1 for each successive one, that identifies a particular configuration.

Listing 2 returns the Index and DHCPEnabled properties for all adapters for which IPEnabled is True.

Scripting Steps

1    Get all WIn32_NetworkAdapterConfiguration elements into an array $netadapters.

2

Retrieve specific instances of the Win32_NetworkAdapterConfiguration class where those adapters which have the IPEnabled property set to is True and assign this to $NetAdaptersIPEnabled. This returns a collection consisting of the network adapter configurations on the computer for which IP is enabled.

3

Pipe this collection to Format-List Cmdlent and display the index of the network adapter and the DHCPEnabled property.

Listing 2   OneSetting-Filter.msh

1
2
3
4    
#OneSetting-Filter.MSH
$NetAdapters = Get-WMIObject Win32_NetworkAdapterConfiguration
$NetAdaptersIPEnabled = $NetAdapters | Where-Object {$_.IPEnabled}
$NetAdaptersIPEnabled| Format-List Index, DHCPEnabled

When you run this script, output similar to the following is displayed in the command window:


Index : 1
DHCPEnabled : True

Index : 11
DHCPEnabled : False

Index : 12
DHCPEnabled : False

 

In some cases, you may want to restrict a script to run against just a single network adapter configuration, i.e. one of the objects in the array of objects. For example, on a dual-homed computer that is connected to two networks, you might want to enable DHCP on one network adapter but not the other. To do this, you could use the select-object with the clause {$_.Index -eq 11} to just return this particular network adapter's configuration."

Scripting Steps

1    Get all WIn32_NetworkAdapterConfiguration Elements elements into an array $NetAdapters
2 Retrieve specific instances of the Win32_NetworkAdapterConfiguration class where those adapters which have the IPEnabled property set to is True and assign this to $NetAdaptersIPEnabled.  This returns a collection consisting of the network adapter configurations on the computer for which IP is enabled.
3 Retrieve the specific network adapter information. This returns an array of one object.
4   Pipe this array to Format-List Cmdlent and display the index of the network adapter and the DHCPEnabled property.

Listing 3   OneSetting-OneNic.msh

1   
2
3
4
5
#OneSetting-OneNic.MSH
$NetAdapters = Get-WMIObject Win32_NetworkAdapterConfiguration
$NetAdaptersipenabled   = $NetAdapters | Where-Object {$_.IPEnabled}
$NetAdaptersIPEnabled12 = $NetAdaptersIPEnabled | Where-Object {$_.Index -eq 12}
$NetAdaptersIPEnabled12 | Format-List Index, DHCPEnabled

When you run this script you should see something like this:


Index : 12
DHCPEnabled : False

Displaying Multi-Valued Properties

Because Windows allows a single network adapter setting to have more than one IP address, subnet mask, default gateway, or DNS server, some properties of Win32_NetworkAdapterConfiguration can have multiple values. WMI returns these multiple values in the form of an array. Because an array contains multiple values, it cannot always be handled in the same way as a single string, Boolean, or number, although MSH does a good job of handling array values.

MSH offers several ways to deal with arrays. First, you simply allow the cmdlet such as Format-Table or Format-List to format the field by default.  The other is to write a For-Each loop. Both of these techniques are demonstrated below.

Using Format-Table/Format-List

When you pipe an array to Format-Table, or Format-List, you can specify the specific properties of an object to print. If this is an array, the cmdlet displays multiple values using normal default rules. In order to demonstrate this, you need to add a second address to an existing network card.

Scripting Steps

1. Get all WIn32_NetworkAdapterConfiguration Elements elements into an array $NetAdapters
2. Retrieve specific instances of the Win32_NetworkAdapterConfiguration class where those adapters which have the IPEnabled property set to is True and assign this to $NetAdaptersIPEnabled.  This returns a collection consisting of the network adapter configurations on the computer for which IP is enabled.
3.For each network adapter configuration in the collection, use the WSH Echo method to display the index of the network adapter.
4.If the IPAddress property (an array):
Is not Null, use the VBScript Join function to concatenate the elements of the IPAddress array into a string with elements separated by a space (the default) and assign them to a variable.
Is Null, assign an empty string to the variable.
5.Display the space-delimited string of IP addresses.

Listing 4   OneSetting-Array.Msh

1   
2
3
4
5
#OneSetting-Array.Msh
$NetAdapters = Get-WMIObject Win32_NetworkAdapterConfiguration
$NetAdaptersipenabled   = $NetAdapters | Where-Object {$_.IPEnabled}
$NetAdaptersIPEnabled12 = $NetAdaptersIPEnabled | Where-Object {$_.Index -eq 12}
$NetAdaptersIPEnabled12 | Format-List Index, DHCPEnabled, IPaddress

When you run this script, output similar to the following is displayed in the command window:


Index : 12
DHCPEnabled : False
IPaddress : {192.168.244.1, 192.168.244.253}
As you can see, MSH displays the IP addresses as an array.
Using ForEach

The Foreach loop provides an alternative way to display the elements of an array but one that gives you more control over the formatting. This statement enables you to iterate through the array, with the script performing an action on each element. In this case, we merely display the element.

Scripting Steps

1. Get all WIn32_NetworkAdapterConfiguration Elements elements into an array $NetAdapters
2. Retrieve specific instances of the Win32_NetworkAdapterConfiguration class where those adapters which have the IPEnabled property set to is True and assign this to $NetAdaptersIPEnabled.  This returns a collection consisting of the network adapter configurations on the computer for which IP is enabled.
3. For each network adapter configuration in the collection, display the index of the network adapter.
4.If the IPAddress property (i.e. the array) is not Null, use a For Each loop to iterate through the IPAddress array, displaying each IP Address in turn

Listing 5 OneSetting-Array-Foreach.msh

1
2
3
4
5
6
7
8
9
10
11
12
13 
     
#OneSetting-Array-Foreach.msh
$NetAdapters = Get-WMIObject Win32_NetworkAdapterConfiguration
$NetAdaptersIPEnabled = $NetAdapters | Where-Object {$_.IPEnabled}
ForEach ($Nic in $NetAdaptersIPEnabled)
{
 "Network Adapter: $($Nic.Index)"
  If ($Nic.IPaddress.length -gt 0) 
 {
   "IP Address(es)"
   foreach ($ipaddr in $nic.IPaddress)
    {" $IPAddr"}
 }
}

When you run this script, output similar to the following is displayed in the command window:

Network Adapter: 1
IP Address(es)
 10.10.1.68
Network Adapter: 11
IP Address(es)
 192.168.235.1
Network Adapter: 12
IP Address(es)
 192.168.244.1
 192.168.244.253
Network Adapter: 13
IP Address(es)
 192.168.244.1
 192.168.244.253

Displaying a Range of Networking Properties

When inventorying network clients, you might often want to gather information about a larger selection of networking settings. For example, you might want to collect the settings displayed in the Advanced TCP/IP Settings dialog box and those shown by Ipconfig.exe. There is overlap between the two but also some differences. A script can combine all the settings from these sources into one package.

For each IP-enabled network adapter on a specific computer, use Ipsettings.msh to obtain the information that displays on the IP Settings tab of the Advanced TCP/IP Settings dialog box for a network connection as well as the information that Ipconfig.exe (used with a few parameters) displays.

A network adapter configuration can have multiple IP addresses, subnets, default gateways, and gateway metrics.

Scripting Steps

1.Create a variable to specify the computer name.
2. Get all WIn32_NetworkAdapterConfiguration Elements elements into an array $NetAdapters
3. Retrieve specific instances of the Win32_NetworkAdapterConfiguration class where those adapters which have the IPEnabled property set to is True and assign this to $NetAdaptersIPEnabled.  This returns a collection consisting of the network adapter configurations on the computer for which IP is enabled.
4. For each network adapter configuration in the collection, display the properties corresponding to the settings on the IP Settings tab.
5.For those properties that return an array, use the .length function to check whether the array is null and if so deal with it.
6.
If the array is If the array is null, display an empty string.

Listing 6   Ipsettings.msh

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.   
 #IPSettings.MSH
 $Computer = "localhost"
 $nicConfigs = gwo Win32_NetworkAdapterConfiguration -Computer $computer | WHERE {$_.IPEnabled}
 ForEach ($Nic In $NicConfigs)
 {
 " Network Adapter $($Nic.Index) - $($Nic.Description)"
 " DHCP Enabled: $($Nic.DHCPEnabled)"
 If ($Nic.IPAddress.length -gt 0)
    {$IPAddr=$Nic.IPAddress}
 Else
    { $IPAddr = ""}
 " IP Address(es): $IPAddr"
 If($Nic.IPSubNet.length -gt 0)
    {$IPsubmet = $Nic.IPSubnet}
 Else
   {$IPSubnet = ""}
 " Subnet Mask(s): $IPSubnet"
 If ($Nic.DefaultIPGateway.lengty -gt 0 )
    {$DefaultIPGateway=$Nic.DefaultIPGateway}
 Else
    {$DefaultIPGateway = ""}
 " Default Gateways(s): $($Nic.DefaultIPGateway)"
 If ($NicConfig.GatewayCostMetric.length -gt 0)
    {$GatewayCostMetric=$NicConfig.GatewayCostMetric}
 Else
    {$GatewayCostMetric = ""}
 " Gateway Metric(s): $($Nic.GatewayCostMetric)"
 " Interface Metric: $($Nic.IPConnectionMetric)"
 " Connection-specific DNS Suffix: $($Nic.DNSDomain)"
 ""
 }

When you  run this script, output similar to the following is displayed in the command window:


  Network Adapter 1 - 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packet Scheduler Miniport
  DHCP Enabled: True
   IP Address(es): 10.10.1.68
   Subnet Mask(s): 255.255.255.0
   Default Gateways(s):         10.10.1.100
   Gateway Metric(s):               
   Interface Metric: 20
  Connection-specific DNS Suffix: kapoho.net

  Network Adapter 11 - VMware Virtual Ethernet Adapter for VMnet1
  DHCP Enabled: False
   IP Address(es): 192.168.235.1
   Subnet Mask(s): 255.255.255.0
   Default Gateways(s):        
   Gateway Metric(s):               
   Interface Metric: 20
  Connection-specific DNS Suffix:

  Network Adapter 12 - VMware Virtual Ethernet Adapter for VMnet8
  DHCP Enabled: False
   IP Address(es): 192.168.244.1 192.168.244.253
   Subnet Mask(s): 255.255.255.0 255.255.255.0
   Default Gateways(s):        
   Gateway Metric(s):               
   Interface Metric: 20
   Connection-specific DNS Suffix:

  Network Adapter 13 - VMware Virtual Ethernet Adapter for VMnet8
  DHCP Enabled: True
   IP Address(es): 192.168.244.1 192.168.244.253
   Subnet Mask(s): 255.255.255.0 255.255.255.0
   Default Gateways(s):        
   Gateway Metric(s):               
   Interface Metric: 20
   Connection-specific DNS Suffix:Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter

The WMI class Win32_NetworkAdapterConfiguration is closely related to another WMI class: Win32_NetworkAdapter. There is a one-to-one correspondence between instances of the two classes and an implicit division of labour between the two classes: Win32_NetworkAdapter exposes mostly hardware-related properties, and in contrast to Win32_NetworkAdapterConfiguration, includes no methods. There is some overlap between the two classes: for example, both have a MACAddress property that retrieves the physical address of a network adapter.

Figure 4 illustrates the relationship between the Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter classes.

The Win32_NetworkAdapter has a NetConnectionID property (available only on Windows XP and Windows Server 2003) that returns the name of the Network Connection (from Network Connections) that is bound to the network adapter, even though such a software setting might more logically belong in Win32_NetworkAdapterConfiguration. This NetConnectionID property corresponds to the name that Ipconfig.exe uses for each network adapter.

In addition, Win32_NetworkAdapter alone includes an AdapterType property that describes the network medium to which the adapter connects, such as Ethernet 802.3 or Token Ring 802.5. Ipconfig.exe also uses this information to describe the network adapter.

Figure 4   Relationship Between These WMI Classes

Figure 4   Relationship Between These WMI Classes
See full-sized image

The following examples show how to display the properties of Win32_NetworkAdapter and also the methods for correlating properties from instances of Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration.

Displaying Network Adapter Properties

Displaying network adapter settings requires similar scripting techniques to those involved in displaying TCP/IP settings. The only difference is that you use the Win32_NetworkAdapterConfiguration class to display TCP/IP settings and the Win32_NetworkAdapter class to display network adapter properties. For more information about the properties and methods for this WMI class, see the WMI Software Development Kit (SDK) topic at http://go.microsoft.com/fwlink/?LinkId=29992.

Scripting Steps

Listing 7 retrieves the properties for all the network adapters on a computer. This script retrieves some properties available only on Windows XP and Windows Server 2003.

1. Create a variable to specify the computer name. For example, to specify the local computer, use ("Localhost").
2. Get all Win32_NetworkAdapterConfiguration Elements elements into an array $NetAdapters
3. For each network adapter in the collection, display the settings

Listing 7   NicSettings.vbs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30   
$Computer = "localhost"
$NetAdapters = gwo Win32_NetworkAdapter $computer
"Network Adapter Settings"
ForEach ($Nic In $NetAdapters)
{ 
  "Network Adapter (Device ID) $($nic.DeviceID)"
  "  Index: $($Nic.Index)"
  "  MAC Address: $($nic.MACAddress)"
  "  Adapter Type: $($nic.AdapterType)"
  "  Adapter Type Id: $($nic.AdapterTypeID)"
  "  Description: $($nic.Description)"
  "  Manufacturer: $nic.Manufacturer"
  "  Name: $($nic.Name)"
  "  Product Name: $($Nic.ProductName)"
  "  Net Connection ID: $($nic.NetConnectionID)"
  "  Net Connection Status: $($nic.NetConnectionStatus)"
  "  PNP Device ID: $($nic.PNPDeviceID)"
  "  Service Name: $($nic.ServiceName)" 
  If ($Nic.NetworkAddresses.length -gt 0) 
     {$add= $Nic.NetworkAddresses}
  Else
    {$add = ""}
  "  NetworkAddresses: $add"
  "  Permanent Address: $($nic.PermanentAddress)"  
  "  AutoSense:  $($nic.AutoSense)"
  "  Maximum Number Controlled: $($nic.MaxNumberControlled)"  
  "  Speed: $($nic.Speed)"
  "  Maximum Speed: $($nic.MaxSpeed)"
  ""
}

When you run this script, output similar to the following is displayed in the command window:


  Network Adapter (Device ID) 1
  Index: 1
    MAC Address: 00:06:5B:83:D3:36
    Adapter Type: Ethernet 802.3
    Adapter Type Id: 0
    Description: 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible)
    Manufacturer: \\WAIMEA\root\cimv2:Win32_NetworkAdapter.DeviceID="1".Manufacturer
    Name: 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible)
    Product Name: 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible)
    Net Connection ID: Local Area Connection
    Net Connection Status: 2
    PNP Device ID: PCI\VEN_10B7&DEV_9200&SUBSYS_00D81028&REV_78\4&19FD8D60&0&58F0
    Service Name: EL90XBC
    NetworkAddresses:
    Permanent Address:
    AutoSense:
    Maximum Number Controlled: 0
    Speed:
    Maximum Speed:

  Network Adapter (Device ID) 2

{{ Listing truncated to save space}}

Associating the Network Connections Name with MAC and IP Addresses Using Two Classes

For various purposes, administrators may need to retrieve the MAC or physical addresses and IP addresses of computers and correlate them with the name of the adapter listed in Network Connections. Ipconfig.exe uses the network adapter name and type to distinguish between network adapters, as shown in Figure 5.

Associating MAC and IP addresses corresponds to the part of the IP routing process performed by the Address Resolution Protocol (ARP). You can view the resulting IP - MAC address translation tables by using the command-line tool Arp.exe. Figure 5 provides an example of the output obtained by running the arp -a command.

Figure 5   Arp.exe output

Figure 5   Arp.exe output
See full-sized image

To use WMI to connect MAC and IP addresses with network adapter names and types, you must correlate properties from corresponding instances of Win32_NetworkAdapterConfiguration (MACAddress and IPAddress) and Win32_NetworkAdapter (NetConnectionID and AdapterType).

Note: The NetConnectionID property of Win32_NetworkAdapter is available only on Windows XP and Windows Server 2003.

In order to find the specific instances of each class that correspond to each other, you can use the Key qualifier to determine key properties for each class. Key properties (there can be more than one) together supply a unique reference for each class instance and are part of the instance namespace handle. They are a little like the key field in a database. The WMI SDK or Wbemtest.exe (the WMI Tester tool, which is included on all versions of Windows that include WMI) can tell you which property or properties of a class are keys.

Table 2 displays the key properties for the two WMI network adapter classes.

Table 2   Key Properties for WMI Network Adapter Classes

 Class Key Property

 Win32_NetworkAdapterConfiguration     

 Index

 Win32_NetworkAdapter

 DeviceID

By using either of these keys, you can match instances of the two classes. In the following example, the Get property of SWbemServices is used to retrieve the instance of Win32_NetworkAdapter, whose DeviceID property corresponds to the Index property of a specific Win32_NetworkAdapterConfiguration instance.

However, MSH's Get-WMIObject cmdlet makes the task much simpler. Calling Get-WMIObject to retrieve these two classes returns two parrallel arrays. The nth member of Win_32NetworkAdapterConfiguration collection returned matches the nth member of the Win32_NetworkAdapter collection. You can therefore use MSH's loop control syntax to loop through the arrays and retreive useful information.

Get-ncmacip.Msh displays the network connection name (or index number for pre-Windows XP clients), MAC address, IP addresses, and subnet masks for IP-enabled network interfaces. A network adapter configuration can have more than one IP address and subnet and these are displayed as previously.

The script shows a simpler way than the GetNetConnectionID() function in Ipsettings.vbs to determine whether the NetConnectionID property is available. Instead of checking the operating system version to see if it is Windows XP (which would ensure that the Win32_NetworkAdapter.NetConnectionID was available), it simply tries to retrieve the NetConnectionID property. If an error is returned, it uses the Win32_NetworkAdapterConfiguration.Index property instead.

Scripting Steps

Listing 9 retrieves the IP addresses and subnet masks for each network adapter on a single computer.

1.Create a variable to specify the computer name.
2. Get all Win32_NetworkAdapter Elements elements into an array $NetAdapters and get all Win32_AdapterConfig elements into $config
3. Iterate through each network adapter configuration in the collection, performing the following steps.
4. If the adapter is configured for IP, then display relevant properties as follows
7.Display the Description property of Win32_NetworkAdapterConfiguration and the MACAddress property of Win32_NetworkAdapter.
8.Display the IPAddress and IPSubnet properties of Win32_NetworkAdapterConfiguration.

Listing 9   Get-ncmacip.Msh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#Get-ncmacip.Msh
$Computer = "localhost"
$Adapters = gwo Win32_NetworkAdapter -comp $Computer
$Config   = gwo Win32_NetworkAdapterConfiguration -comp $Computer
"MAC & IP Addresses & Subnet Masks"
For($i=0;$i -lt $Adapters.length;$i++) 
 {
  if ($config[$i].ipenabled)
  {
    "$($Adapters[$i].AdapterType) $($Adapters[$i].NetConnectionID)"

    " Network Adapter $($Adapters[$i].Index)"
    " $($Adapters[$i].Description)"
    " MAC Address: $($Adapters[$i].MACAddress)"
    " IP Address(es): $($Config[$i].IPAddress)"
    " Subnet Mask(s): $($Config[$i].IPSubnet)"
    ""
   }
 }

When you run this script, output similar to the following is displayed in the command window:

[c:\scripts]: .\Get-ncmacip.Msh
MAC & IP Addresses & Subnet Masks
Ethernet 802.3 Local Area Connection
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible)
MAC Address: 00:06:5B:83:D3:36
IP Address(es): 10.10.1.68
Subnet Mask(s): 255.255.255.0

Ethernet 802.3 VMware Network Adapter VMnet1
Network Adapter 11
VMware Virtual Ethernet Adapter for VMnet1
MAC Address: 00:50:56:C0:00:01
IP Address(es): 192.168.235.1
Subnet Mask(s): 255.255.255.0

Ethernet 802.3 VMware Network Adapter VMnet8
Network Adapter 12
VMware Virtual Ethernet Adapter for VMnet8
MAC Address: 00:50:56:C0:00:08
IP Address(es): 192.168.244.1 192.168.244.253
Subnet Mask(s): 255.255.255.0 255.255.255.0

Displaying Expanded IP Configuration Data

In Windows XP, a convenient way to retrieve more detailed TCP/IP client settings is through the Network Connections Details dialog box for a specific network connection.

To retrieve detailed TCP/IP settings for a specific network connection

1.Open Control Panel and then double-click Network Connections.
2.In the Network Connections dialog box, right-click a specific network connection and then click Status.
3.On the Support tab, click Details to view network connection settings.

Figure 7 shows an example of a Network Connection Details box.

Figure 7   Network Connection Details Dialog Box

Figure 7   Network Connection Details Dialog Box
See full-sized image

Using Ipconfig.exe to Display Expanded Configuration Data

You can use the /all option with the Ipconfig.exe command-line tool to retrieve a collection of settings even more detailed than those in the Network Connections Details dialog box. Figure 8 shows screen output like what displays when you use the ipconfig /all command.

Figure 8   Using Ipconfig.exe /all to Display Network Data

Figure 8   Using Ipconfig.exe /all to Display Network Data
See full-sized image

Using a Script to Display Expanded Configuration Data

WMI provides the functionality to reproduce nearly all the functionality of the ipconfig /all command, along with many other settings. Besides Win32_NetworkAdapterConfiguration, Ipconfig.vbs also uses StdRegProv, which is a class included in the System Registry WMI provider, to extract some settings from the registry.

Caution
Incorrectly editing the registry may severely damage your system. Before making changes to the registry, you should back up any valued data on the computer.

Scripting Steps

Listing 12 retrieves an extensive set of TCP/IP network client properties, equivalent to those retrieved by Ipconfig.exe /all, from a single computer. The script uses two functions: one that converts the dates returned to a more readable format and another that returns the operating system version.

To carry out these tasks, the script must:

1.Invoke On Error Resume Next so that errors do not terminate the script.
2.Assign values to constants and variables to be used.
3.Use a GetObject call to connect to the StdRegProv class in the WMI namespace root\default.
4.Retrieve global settings from the registry by using the GetStringValue and GetDWORDValue methods of StdRegProv. These settings apply to all network adapters.

These methods return a value in an out parameter, the final parameter for each method.

5.Use a Select Case statement to decode the value returned by the dwNodeType out parameter.
6.Use an If ... ElseIf ... Else statement to decode the value returned by the dwIPRouting out parameter.
7.Use a GetObject call to connect to the WMI namespace root\cimv2.
8.Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

This returns a collection consisting of all the network adapter configurations on the computer for which IP is enabled.

9.Retrieve the value of DNSEnabledForWINSResolution, which is a global setting, the same for each network adapter. Use an If ... ElseIf ... Else statement to decode the Boolean value returned by DNSEnabledForWINSResolution.
10.Display the global settings retrieved.
11.Again use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”
12.Call the GetOSVer function, which gets the Version property of Win32_OperatingSystem. Assign the value returned to a variable.
13.Iterate through each network adapter configuration in the collection returned by the query.
14.Retrieve the Index property for the instance and use the Get method to return the instance of Win32_NetworkAdapter whose DeviceID property corresponds to the value of Index.
15.Retrieve the per-adapter properties of Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration displayed by Ipconfig.exe /all.
16.If the AdapterType property is not available, display "Network" as the adapter type.
17.If the operating system version is:
Greater than 5, indicating Windows XP or Windows Server 2003, retrieve the NetConnectionID property from Win32_NetworkAdapter.
5 or less, use the Index property of Win32_NetworkAdapterConfiguration as the identifier of the network adapter.
18.Retrieve and display other properties of the two classes.
19.If the property returns an array, check that the value is not null. If the return value is not null, assign each array element, separated by a space, to a string, and display the string.
20.If the property returns a value in WMI DATETIME format, call the WMIDateStringToDate function and pass it the DATETIME value.

This function converts the value to a more readable string representing the date and time.

Listing 12   Ipconfig.vbs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
On Error Resume Next
 
 
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
strKeyPath1 = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
strKeyPath2 = "SYSTEM\CurrentControlSet\Services\NetBT\Parameters"
strHostEntry = "Hostname"
strDomainEntry = "Domain"
strNodeEntry = "DhcpNodeType"
strRoutingEntry = "IPEnableRouter"
 
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
 strComputer & "\root\default:StdRegProv")
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath1,strHostEntry,strHostname
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath1,strDomainEntry,strDomain
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath2,strNodeEntry,dwNodeType
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath1,strRoutingEntry,dwIPRouting
 
Select Case dwNodeType
  Case 4 strNodeType = "Mixed"
  Case 8 strNodeType = "Hybrid"
  Case Else strNodeType = dwNodeType
End Select
If dwIPRouting = 0 Then
  strIPRouting = "No"
ElseIf dwIPRouting = 1 Then
  strIPRouting = "Yes"
Else
  strIPRouting = "?"
End If
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
 
Set colFirstNicConfig = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objFirstNicConfig In colFirstNicConfig
  strDnsWins = objFirstNicConfig.DNSEnabledForWINSResolution
Next
If strDnsWins = False Then
  strWinsProxy = "No"
ElseIf strDnsWins = True Then
  strWinsProxy = "Yes"
Else
  strWinsProxy = "?"
End If
 
' Display global settings.
 
WScript.Echo VbCrLf & "Windows IP Configuration" & VbCrLf
WScript.Echo "        Host Name . . . . . . . . . . . . : " & strHostname
WScript.Echo "        Primary DNS Suffix  . . . . . . . : " & strDomain
WScript.Echo "        Node Type . . . . . . . . . . . . : " & strNodeType
WScript.Echo "        IP Routing Enabled. . . . . . . . : " & strIPRouting
WScript.Echo "        WINS Proxy Enabled. . . . . . . . : " & strWinsProxy
WScript.Echo "        DNS Suffix Search List. . . . . . : " & strDomain
 
Set colNicConfigs = objWMIService.ExecQuery _
  ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
sngOsVer = GetOsVer
 
' Display per-adapter settings.
 
For Each objNicConfig In colNicConfigs
  intIndex = objNicConfig.Index
  Set objNic = objWMIService.Get("Win32_NetworkAdapter.DeviceID=" & intIndex)
 
  strAdapterType = objNic.AdapterType
  If IsEmpty(strAdapterType) Or IsNull(strAdapterType) Or _
   (strAdapterType = "") Then
    strAdapterType = "Network"
  End If
 
  If sngOsVer > 5 Then
    strNetConn = objNic.NetConnectionID
  Else
    strNetConn = intIndex
  End If
 
  WScript.Echo VbCrLf & strAdapterType & " adapter " & strNetConn
  WScript.Echo "        Connection-specific DNS Suffix  . : " & _
   objNicConfig.DNSDomain
  WScript.Echo "        Description . . . . . . . . . . . : " & _
   objNicConfig.Description
  WScript.Echo "        Physical Address. . . . . . . . . : " & _
   objNicConfig.MACAddress
  WScript.Echo "        DHCP Enabled. . . . . . . . . . . : " & _
   objNicConfig.DHCPEnabled
'  WScript.Echo "        Autoconfiguration Enabled . . . .: " & objNicConfig.?
 
  strIPAddresses = ""
  If Not IsNull(objNicConfig.IPAddress) Then
    For Each strIPAddress In objNicConfig.IPAddress
      strIPAddresses = strIPAddresses & strIPAddress & " "
    Next
  End If
  WScript.Echo "        IP Address. . . . . . . . . . . . : " & strIPAddresses
  strIPSubnets = ""
  If Not IsNull(objNicConfig.IPSubnet) Then
    For Each strIPSubnet In objNicConfig.IPSubnet
      strIPSubnets = strIPSubnets & strIPSubnet & " "
    Next
  End If
  WScript.Echo "        Subnet Mask . . . . . . . . . . . : " & strIPSubnets
  strDefaultIPGateways = ""
  If Not IsNull(objNicConfig.DefaultIPGateway) Then
    For Each strDefaultIPGateway In objNicConfig.DefaultIPGateway
      strDefaultIPGateways = strDefaultIPGateways & strDefaultIPGateway & " "
    Next
  End If
  WScript.Echo "        Default Gateway . . . . . . . . . : " & _
   strDefaultIPGateways
  WScript.Echo "        DHCP Server . . . . . . . . . . . : " & _
   objNicConfig.DHCPServer
  strDNSServerSearchOrder = ""
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      strDNSServerSearchOrder = strDNSServerSearchOrder & VbCrLf & _
      "                                            " & strDNSServer
    Next
  End If
  WScript.Echo "        DNS Servers . . . . . . . . . . . :" & _
   strDNSServerSearchOrder
  If Not IsNull(objNicConfig.WINSPrimaryServer) Then
    WScript.Echo "        Primary WINS Server . . . . . . . : " & _
     objNicConfig.WINSPrimaryServer
  End If
  If Not IsNull(objNicConfig.WINSSecondaryServer) Then
    WScript.Echo "        Secondary WINS Server . . . . . . : " & _
     objNicConfig.WINSSecondaryServer
  End If
  If objNicConfig.DHCPEnabled Then
    dtmRawLeaseObtainedDate = objNicConfig.DHCPLeaseObtained
    strFormattedLeaseObtainedDate = WMIDateToString(dtmRawLeaseObtainedDate)
    WScript.Echo "        Lease Obtained. . . . . . . . . . : " & _
     strFormattedLeaseObtainedDate
    dtmRawLeaseExpiresDate = objNicConfig.DHCPLeaseExpires
    strFormattedLeaseExpiresDate = WMIDateToString(dtmRawLeaseExpiresDate)
    WScript.Echo "        Lease Expires . . . . . . . . . . : " & _
    strFormattedLeaseExpiresDate
  End If
Next
 
'******************************************************************************
' Function: WMIDateStringToDate(dtmDate)
' Converts WMI date to string.
'******************************************************************************
 
Function WMIDateToString(dtmDate)
    WMIDateToString = CDate(Mid(dtmDate, 5, 2) & "/" & _
                      Mid(dtmDate, 7, 2) & "/" & _
                      Left(dtmDate, 4) & " " & _
                      Mid(dtmDate, 9, 2) & ":" & _
                      Mid(dtmDate, 11, 2) & ":" & _
                      Mid(dtmDate, 13, 2))
End Function
 
'******************************************************************************
' Function: GetOsVer
' Gets the operating system version number.
'******************************************************************************
 
Function GetOsVer
  Set colOperatingSystems = objWMIService.ExecQuery _
   ("Select * from Win32_OperatingSystem")
  For Each objOperatingSystem In colOperatingSystems
    GetOSVer = CSng(Left(objOperatingSystem.Version, 3))
  Next
End Function

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>ipconfig.vbs

 

Windows IP Configuration

        Host Name . . . . . . . . . . . . . . : client1
        Primary DNS Suffix  . . . . . . . : fabrikam.com
        Node Type . . . . . . . . . . . . . . : Hybrid
        IP Routing Enabled. . . . . . . . : No
        WINS Proxy Enabled. . . . . . . : Yes
        DNS Suffix Search List. . . . . . : fabrikam.com

Ethernet 802.3 adapter Local Area Connection
        Connection-specific DNS Suffix  . :
        Description . . . . . . . . . . . : 3Com 3C920 Integrated Fast Ethernet
Controller (3C905C-TX Compatible) - Packet Scheduler Miniport
        Physical Address. . . . . . . . . : 00:B0:D0:23:70:37
        DHCP Enabled. . . . . . . . . . . : True
        IP Address. . . . . . . . . . . . : 192.168.0.12

        Subnet Mask . . . . . . . . . . . : 255.255.255.0

        Default Gateway . . . . . . . . . : 192.168.0.1

        DHCP Server . . . . . . . . . . . : 192.168.0.1

        DNS Servers . . . . . . . . . . . :

                                                   192.168.0.1

        Primary WINS Server . . . . . . . : 192.168.0.1

        Secondary WINS Server . . . . . . : 192.168.0.2

        Lease Obtained. . . . . . . . . . . . . : 6/2/2004 4:31:19 PM

        Lease Expires . . . . . . . . . . . . . : 6/12/2004 7:31:19 PM

Top of pageTop of page

Tools for Basic TCP/IP Networking on Clients

The tables in this section list the available command-line and scripting tools, and registry keys for retrieving and displaying basic networking data on clients. Table 3 lists the command-line tools for displaying basic TCP/IP networking on clients and also indicates where you find the tools.

Table 3   Command-Line Tools for Basic TCP/IP Networking on Clients

Tool Where Available

Arp.exe

Windows operating systems1

Getmac.exe: GetMAC

Windows 2000 Resource Kit

Hostname.exe

Windows operating systems

Ipconfig.exe

Windows operating systems

Listadapters.vbs

Windows 2000 Resource Kit

Netconnections.vbs

Windows 2000 Resource Kit

Netipconfig.pl

Windows 2000 Resource Kit

Netipfilteringconfig.pl

Windows 2000 Resource Kit

Net.exe

Windows operating systems

Netset.exe

Windows 2000 Resource Kit

Netsh.exe

Windows operating systems

Netstat.exe

Windows operating systems

Networkprotocol.vbs

Windows 2000 Resource Kit

Ping.exe

Windows operating system

Protocolbinding.vbs

Windows 2000 Resource Kit

Subnet_op.vbs

Windows 2000 Resource Kit

Timezone.exe: Daylight Saving Time Update Utility

Windows 2000 Resource Kit

Tzedit.exe: Time Zone Editor

Windows 2000 Resource Kit -- GUI tool

Wsremote.exe

Windows XP Support Tool

1 Windows 2000, Windows XP, and Windows Server 2003. May also be present on other versions of Windows.

Table 4 lists the WSH objects and WMI classes for displaying basic TCP/IP networking on clients and also provides notes and availability information.

Table 4   WSH Objects and WMI Classes for Basic TCP/IP Networking on Clients

TechnologyObject or ClassNotes

WMI

Win32_ComputerSystem

 

WMI

Win32_NetworkAdapterConfiguration

 

WMI

Win32_NetworkAdapter

 

WMI

Win32_NetworkAdapterSetting

Association class associating Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration

WMI

Win32_NetworkClient

 

WMI

Win32_NetworkConnection

 

WMI

Win32_NetworkProtocol

 

WMI

Win32_NTDomain

Windows XP and Windows Server 2003 only

WMI

Win32_OperatingSystem

 

WMI

Win32_PingStatus

Windows XP and Windows Server 2003 only

WMI

Win32_ProtocolBinding

Association class associating Win32_NetworkProtocol, Win32_SystemDriver, and Win32_NetworkAdapter

Table 5 lists the registry keys to use for displaying basic TCP/IP networking on clients.

caution.gif  Caution
Incorrectly editing the registry may severely damage your system. Before making changes to the registry, you should back up any valued data on the computer.

Table 5   Registry Subkeys Related to Basic TCP/IP Networking on Clients

Registry Subkeys

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dhcp

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dnscache

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBIOS

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBT

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Netman

 


Visitors:

Last Updated: 24-07-05 09:11 PM +0100