Automating TCP/IP Networking on ClientsOverview
Published: September 1, 2004By Peter Costantini, the Microsoft Scripting Guys
Windows scripting technologies enable system administrators to automate many common tasks
involved in managing TCP/IP network clients. This paper discusses scripting techniques and shows
scripting examples for:
• Retrieving TCP/IP client settings.
• Working with remote hosts.
• Configuring DHCP and static IP addresses.
• Managing DNS client settings.
• Working with NetBIOS and WINS.
Also included are scenarios that combine basic techniques to create sample solutions for more
complex networking tasks.
• Part 1: Introduction
Introduces the scope and organization of the paper, assumptions about technical level of readers,
information on how to use the example scripts, and system requirements.
• Part 2: Scripting Basic TCP/IP Networking on Clients
Compares using the Windows graphical user interface, command-line tools, and scripting to retrieve
and display TCP/IP client data.
• Part 3: Scripting Remote Network Management
Illustrates scripting techniques for working with TCP/IP settings on multiple remote clients with WMI.
• Part 4: Scripting IP Address Allocation on Clients
Illustrates how to manage DHCP and static IP address settings on clients with scripting.
• Part 5: Scripting DNS on Clients
Illustrates how to manage DNS settings on clients with scripting.
• Part 6: Scripting WINS on Clients
Illustrates how to manage NetBIOS and WINS settings on clients with scripting.
• Part 7: Scripting Other Network Protocols
Illustrates how to manage TCP/IP filtering, other TCP/IP settings, IPX, and network protocols on
clients with scripting.
• Part 8: Using Advanced Scripting Techniques to Manage Networks
Illustrates how to use advanced scripting techniques on clients to manage time settings and change
other TCP/IP settings in the registry.
• Part 9: Scenario for Adding New
ClientsAnalyzes a script that can add, remove and change network clients and their TCP/IP settings.
• Part 10: Resources for Scripting Network Management
Describes useful books and Internet resources for scripting TCP/IP settings on network clients.
Acknowledgements
I would like to thank the following people for their contributions and support:
My fellow Scripting Guys: Greg Stemp, Dean Tsaltas, Bob Wells, Ethan Wilansky, and Mary Gray
Writing Manager: David Mills
Publishing Team: Chris Blanton, Jody Ivy, Jon Billow, and Kim McGhee
Testing: Richard Min and Larry Petersen
Content Testing: Bob Thingwold and Richard Rice
A special thanks for their valuable comments and suggestions to:
Ross Carter
Joseph Davies
Steve Lee
Scott McNairy
David Meyer
Michael Murgolo
Mike Poulson
David Powell
Ben Shy
Levi Stevens
Don Marshall, Attachmate Corporation
Randy Brown, Attachmate Corporation
Bill Duncan, Attachmate Corporation
Steve Cathersall, Vulcan, Inc.
J.C. Warren, Vulcan, Inc.
Greg Katsel, Vulcan, Inc
Automating TCP/IP Networking on ClientsPart 1: Introduction
Published: July 19, 2004Looking down from the CIO's office, networks based on Transmission Control Protocol/Internet
Protocol (TCP/IP) are the nervous systems of many organizations. Their healthy functioning is critical
to corporate communications, customer satisfaction, employee morale, and the bottom line.
Because of the scale and complexity of such networks and the accessibility of the TCP/IP protocol
stack to scripting, the tasks involved in configuring and maintaining TCP/IP networking components
are often good candidates for automation.
Looking up from the administrative trenches, the work of managing a TCP/IP network sometimes
seems to consist of hours of drudgery interrupted by moments of frantic damage control. This paper
primarily discusses ways to make those uneventful hours pass in a more reliable, structured, and
productive way, which should help reduce the incidence of crises in the bargain.
By scripting administrative operations, you can relieve the boredom of repetitious tasks and free
more time to deal with less routine issues. Replacing manual procedures, which run the risk of
operator error or forgetfulness, with automated maintenance can also alleviate the risk of attacks by
malicious viruses and worms and of hardware failures. Scheduling your scripts to run during off-peak
hours and without administrator intervention can relieve network traffic jams and reduce user
inconvenience. Overall, a well-designed ensemble of scripts, in concert with appropriate Microsoft®
Windows® graphical user interface (GUI) and command-line tools, can standardize and systematize
network operations, increasing productivity, reliability, and morale.
As with most useful things, the kind of scripting discussed in this paper has associated costs. The
language, Microsoft® Visual Basic® Scripting Edition (VBScript); the scripting environment,
Microsoft® Windows® Script Host (WSH); and the automation library, Windows Management
Instrumentation (WMI), typically involve more study to master than the GUI or command-line tools.
Nevertheless, although scripting is a form of programming, it is one that does not require four years
of computer science study to become proficient and productive. Thousands of system
administrators and engineers around the world have learned scripting, used it to great advantage,
extended it, and now constitute a community that offers Web sites, newsgroups, and other
invaluable resources for those who want to profit from their experience.
On This Page
Scope and Organization of This Paper
Running the Sample Scripts
System Requirements
Other Important Resources
Scope and Organization of This PaperThe Windows operating system family provides a variety of tools for managing TCP/IP networks. This
paper focuses on the tools that enable you to automate tasks on TCP/IP clients. It covers scripting
tools and techniques that enable you to work with the client side of most important elements of
TCP/IP networking, including Dynamic Host Configuration Protocol (DHCP), Domain Name System
(DNS), and Windows Internet Name Service (WINS). Each section provides detailed explanations and
script examples, with relevant command-line tools and registry keys listed in tables at the end.
Beginning with basic scripting techniques, this paper shows increasingly complex variations that
open up new functionality. In some areas, it discusses common practical scenarios that require
combining different scripting approaches. Its aim, however, is not to show cool scripting tricks for
their own sake, but rather to provide flexible ways to automate real-world networking tasks that
commonly confront system administrators.
This paper covers the following topics:
• Scripting basic TCP/IP networking on clients, including comparisons of GUI and command-line tools
to analogous scripting techniques.
• Extending these scripting techniques to remote and multiple computers.
• Scripting IP address allocation with DHCP and static IP addresses.
• Scripting DNS client management.
• Scripting WINS client management.
• Scripting TCP/IP filtering, Internetwork Packet Exchange (IPX), and other network protocols.
• Advanced scripting techniques that include managing system time and scripting network settings in
the registry.
• A final scenario that combines many previously illustrated techniques in a complex script that adds
new clients to a network.
• A list of important resources that can help you in scripting network clients.
Use of VBScript, WSH, and WMI in Scripting ExamplesBecause VBScript is the most popular language for automating Windows administration, all script
examples in this paper are written in this language. If you prefer to work in Microsoft JScript®, Perl,
or another scripting language, the translation in most cases is simple, because similar techniques
apply. These scripts all run under Windows Script Host, the Windows administrative scripting
environment; so you can use any language for which a WSH scripting engine is available.
VBScript and WSH, however, provide only the language and environment for scripting. Most of the
functionality for retrieving configuration information and making changes is included in WMI, which
provides hundreds of classes that allow you to work with hardware and software.
This paper focuses on just a few WMI classes — ones that include nearly all the TCP/IP client
functionality in WMI. The most important class is Win32_NetworkAdapterConfiguration, which
contains most of the settings that this paper discusses. Instances of
Win32_NetworkAdapterConfiguration have a one-to-one relationship to instances of
Win32_NetworkAdapter; in other words, each object representing the configuration settings for a
network adapter has a corresponding object representing the hardware of that network adapter.
Win32_NetworkAdapterSetting, an association class, represents the relationship between the
previous two classes.
Win32_NetworkAdapterConfiguration includes 61 read-only properties and 41 methods for changing
the properties; Win32_NetworkAdapter and Win32_NetworkAdapterSetting, on the other hand,
contain only read-only properties.
Table 1 highlights these important classes as well as a few additional classes that contain varying
numbers of read-only properties. Among them, only Win32_ComputerSystem and
Win32_OperatingSystem contain methods and a few read/write properties.
Table 1 WMI Classes That Provide TCP/IP Client Functionality
WMI Class Properties NotesWin32_NetworkAdapterConfiguration 61 read-only
properties;
41 methods for
changing properties
The most important class for scripting
TCP/IP tasks. Contains most of the
settings discussed in this paper.
Win32_NetworkAdapter Read-only properties Has a one-to one relationship with
instances of
Win32_NetworkAdapterConfiguration
Win32_NetworkAdapterSetting Read-only properties An association class that represents the
relationship between the
Win32_NetworkAdapterConfiguration
and Win32_NetworkAdapter classes.
Win32_NetworkProtocol Read-only properties
Win32_ComputerSystem Some read-only and a
few read/write
properties;
some methods
Win32_OperatingSystem Some read-only and a
few read/write
properties;
some methods
Win32_PingStatus Read-only properties
Win32_LocalTime Read-only properties
Win32_UTCTime Read-only properties
Win32_TimeZone Read-only properties
Although the names of the WMI classes Win32_NetworkClient, Win32_NetworkConnection, and
Win32_NetworkLoginProfile suggest a relationship to topics in this paper, these classes are not
directly relevant to our subject matter. Win32_NetworkConnection, for example, retrieves settings
relating to shared network resources currently connected to the computer — not the kind of network
connections managed by Network and Dial-up Connections.
This paper provides many but not all details about selected WMI classes. For more detailed
information about WMI classes, including a more complete list of classes, see the WMI SDK on the
Microsoft Developers Network (MSDN) at http://go.microsoft.com/fwlink/?LinkId=24766.
Technical Level of This PaperThis paper is intended for system and network administrators, engineers, and architects who use or
want to use scripting in their work. It assumes some familiarity with scripting and a basic level of
networking knowledge. Although it does not try to teach basic scripting or networking, it does
explain scripting techniques in detail as they are used.
What This Paper Does Not CoverThis paper does not cover basic scripting or basic TCP/IP networking. To learn basic system
administration scripting techniques, see the Microsoft® Windows® 2000 Scripting Guide and the
many example scripts on the TechNet Script Center at http://go.microsoft.com/fwlink/?
LinkId=24771. For information about TCP/IP networking on Windows, see Microsoft® Windows
Server™ Help, which is included with your Windows Server operating system, and the Microsoft®
Windows 2000 Server Resource Kit.
The scope of this paper is restricted to scripting TCP/IP clients. Scripting DHCP, DNS, and WINS
servers, routers, and network monitoring are not covered.
The related subjects of scripting domain administration and directory services are also not covered
in this paper. However, you can find some content relevant to these topics in the Windows 2000
Scripting Guide and also in the example scripts on the TechNet Script Center at
http://go.microsoft.com/fwlink/?LinkId=24771.
Note
This paper covers only scripting for IPv4 networks; it does not provide script examples for IPv6
networks.
Command-Line Tools and Batch FilesBecause this paper focuses on scripting WMI with VBScript and WSH, it does not describe how to use
the command-line tools included with the Windows operating system or the Windows 2000 Resource
Kit; nor does it cover how to write batch files. Those topics are covered in the documentation for
those products and in many other books.
At the end of each section, however, a tools section lists the relevant command-line tools.
Organization of ScriptsThe sample scripts in this paper follow some general patterns:
Constants and variablesIn most cases, constants and some variables (usually ones that you want to change) are initialized
at the beginning of the script. However, not all variables are initialized before they are used. Almost
no variables are declared because VBScript does not require it, which helps keep the scripts shorter.
As a debugging aid when writing your own scripts, you may want to explicitly declare all variables
with the Dim statement and verify this with the Option Explicit statement.
Connecting to the WMI serviceNearly all scripts begin by connecting the WMI service and then getting a reference to instances of
one or more WMI classes.
Linear execution pathMost scripts follow a relatively linear execution path to make them simpler and easier to follow. Only
a few of the longer and more complex scripts are broken down into subroutines and functions.
In some situations, a modular approach may be more adaptable and flexible. If you think you will
use a section of code more than once or if you might call it from different places in the script,
consider transforming that section of code into a subroutine or function that you can reuse in other
scripts.
For IT groups where more than one person writes or uses scripts, standardizing scripting formats
and conventions can help to reduce confusion and improve code consistency.
VBScript error handlingScripts that make changes or that connect to remote computers use the VBScript On Error Resume
Next statement along with simple forms of error handling. On Error Resume Next masks errors in
the script by allowing the script to continue execution after the line on which the error occurred.
When debugging, it can be helpful to temporarily comment out the On Error Resume Next
statement by putting a single quotation mark (') at the beginning of the line. Commenting out this
statement causes any errors to result in termination of the script with an error message, which can
help you locate problems.
Most such scripts check to see if the computer is available on the network. If it is, they also check to
see if they can connect to the WMI service on that computer because clients with older versions of
the operating system might not have WMI installed. You may want to add more robust error
handling in other areas where you expect to encounter frequent run-time errors.
Sample scripts are code examples, not tools
The sample scripts in this paper are offered as code examples that focus on one or a few tasks. You
can dissect, analyze, and recombine these samples to create scripts that meet your own needs.
These scripts are not designed as complete, robust tools capable of accomplishing many different
tasks and handling many contingencies.
An implicit assumption behind the scripts is that they will be run by administrators with some
knowledge of scripting, who are capable of editing scripts to change parameters, where necessary.
With few exceptions, the scripts do not accept command-line arguments, as many of the more
complex scripts included with Windows do, and they do not try to handle all contingencies or
possible errors.
Caution
Sample scripts are not designed to be run as is or by non-scripting support personnel or end users.
Top of page
Running the Sample ScriptsTo run any of the sample scripts contained in this paper, follow these steps:
1. Log on with required administrative credentials.
2. Copy the script code to a text file
3. Save it with a .vbs extension.
Important
Do not copy the line numbers that appear in the left margin (along the left side of most sample
scripts).
4. Open a command prompt and navigate to the folder where the script is located.
In this paper, the script is always assumed to be in C:\Scripts; however, you can place the script in
any folder.
When you set up your scripting environment, it is recommended that you set the WSH default script
host to Cscript.exe, the command-line version, because all these scripts are designed to run at the
command prompt. How to do this is explained below.
Important
If you use Wscript.exe, which is the GUI scripting host, each piece of script output will open a popup
that you must then close. This can be time-consuming when a script produces a lot of output and
prevents scripts from running unattended.
If you are running a script that makes changes, be sure to save your current settings before making
changes. How to do this is explained below.
Running Scripts with Administrative CredentialsWindows, WSH, and WMI security require that you use local Administrator credentials to run scripts
on local or remote computers not joined to a domain. On computers joined to a domain, you can
also use domain administrator credentials. You cannot do anything with a script that is run under
your credentials that you could not do with a command-line tool or in the Windows interface.
For more information about security requirements for scripting, see “Tales from the Script –
September 2003: Transform Your Workstation into a Scripting Dynamo” on Microsoft TechNet at
http://go.microsoft.com/fwlink/?LinkId=24767.
Setting the Default Script Host to CscriptTo set the default script host to Cscript, suppress the logo (a couple of lines of unnecessary output),
and save these settings as the default, run the following at a command prompt:
cscript //h:cscript //nologo //s
Most of the sample scripts in this paper run against the local computer, which is represented to WMI
by the dot or period character (.). In some scripts, values such as computer names or IP addresses
are hard-coded into variables near the top of the script. To run these scripts on your computer or
network, you must first change these values to match your network and host configurations. These
required changes are explained along with each script.
Saving Current Settings Before Running Scripts That Make ChangesSome sample scripts make changes on the computer against which they are run. These scripts are
flagged with a caution like the one that follows.
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Before running a script that makes changes, it is a good idea to save all current IP settings in a text
file. You can do this by running the following command line:
ipconfig.exe /all > ipconfig.txt
This command line redirects the output of ipconfig into a text file in the same folder from which
you have run the command.
In addition to the ipconfig command, some sections of this paper begin with a script that displays
the settings for that networking area. You can use Ipsettings.vbs, Dhcpsettings.vbs,
Dnssettings.vbs, and Winssettings.vbs to capture configurations for these areas before running a
script that may change them.
Top of page
System RequirementsThis paper assumes you are running the scripts on Windows 2000, Windows XP, or Windows
Server 2003. Most of the WMI functionality discussed here is available on Windows 2000. However,
Windows XP and Windows Server 2003 do include a number of useful new classes, properties, and
methods, some of which are illustrated here. System requirements more stringent than the previous
will be noted in each section.
Whenever possible, run the most recent versions of WSH and VBScript, version 5.6 build 8515, both
of which are included in the Windows Script download on MSDN at http://go.microsoft.com/fwlink/?
LinkId=27639. This download is available for Microsoft® Windows XP, Windows® 2000,
Windows® Millennium Edition (Me), Windows NT® Server 4.0, and Windows® 98.
The versions of WMI and Active Directory Service Interfaces (ADSI) depend on the operating system
that a computer is running. Microsoft® Windows® Millennium Edition and later versions of the
operating system all include WMI. For Windows NT Server 4.0 and Windows 98, you can download
WMI version 1.5 from MSDN. For Windows NT Server 4.0 and Windows 98, you can download Active
Directory Client Extensions, which allow these operating systems to function as Active D
Automating TCP/IP Networking on ClientsPart 2: Scripting Basic TCP/IP Networking on Clients
Published: July 19, 2004In some kinds of IT environments, such as convention centers, hotels, and universities, network
administrators must frequently change network client information because transient users and
computers come and go. In these kinds of computing environments, using scripts to configure
network clients may prove particularly useful. Even on less turbulent 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 2000 and
Network Connections in Windows XP and Windows Server 2003 (in Control Panel), you can view and
modify most network settings. Widely used command-line tools such as Ipconfig.exe and Ping.exe
provide additional options. 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 and changing 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.
On This Page
Retrieving Basic TCP/IP Client Settings by Using Non-Scripting Methods
Retrieving Basic Settings with a Script
Displaying Expanded IP Configuration Data
Tools for Basic TCP/IP Networking on Clients
Retrieving Basic TCP/IP Client Settings by Using Non-Scripting MethodsTo 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 XP through Network Connections and in
Windows 2000 through Network and Dial-Up Connections.
To check TCP/IP settings by using the Windows interface in Windows XP
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
See full-sized image
The DNS, WINS, and Options tabs also display settings for those technologies and enable you to
change most settings.
Getting Basic Settings by Using Ipconfig.exeMany administrators use command-line tools to obtain TCP/IP client configuration information. One
popular command-line tool is Ipconfig.exe, which is included with the Windows operating system.
Figure 2 illustrates the network settings you can display by using Ipconfig.exe.
Figure 2 Typical Network Settings Displayed by Ipconfig.exe
See full-sized image
You can use this tool not only to display networking settings but also to perform certain operations.
For example, the /renew option renews DHCP leases and the /flushdns option purges the DNS
client resolver cache.
Top of page
Retrieving Basic Settings with a ScriptBy writing scripts in VBScript that use WSH and WMI, 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
See full-sized image
For purposes of scripting, a WMI class is simply a way of packaging a related set of configuration
settings and configuring them into a bundle with a recognizable name. Scripts call the properties to
retrieve the settings and methods in order to change them.
Win32_NetworkAdapterConfiguration also 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 ClassThe 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 VBScript 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.
Calling the InstancesOf() or ExecQuery() methods of the SWbemServices object on
Win32_NetworkAdapterConfiguration returns a collection of objects. This collection is in the form of
an SWbemObjectSet collection containing zero or more SWbemObject instances. These objects and
methods are documented in detail in the WMI Reference of the WMI SDK under "Scripting API for
WMI."
Displaying One SettingThe 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 values used by VBScript are -1 for true and 0 for false; however, any
non-zero value can be used programmatically to represent true. In most cases, scripts should use
True and False, which are the two VBScript keywords, to represent these values.
The pattern used in this simple script can be repeated for any property of
Win32_NetworkAdapterConfiguration except for those that return arrays. Handling properties that
return arrays is discussed later in this paper.
Scripting Steps
1. Connect to the WMI service using the "winmgmts:" moniker.
2. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the
InstancesOf method.
This returns a collection consisting of all the network adapter configurations on the computer.
3. For each network adapter configuration in the collection, use the WSH Echo method to 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.
Listing 1 Onesetting.vbs
1
2
3
4
5
6
Set objWMIService = GetObject("winmgmts:")
Set colNicConfig = _
objWMIService.InstancesOf("Win32_NetworkAdapterConfiguration")
For Each objNicConfig In colNicConfig
WScript.Echo objNicConfig.DHCPEnabled
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>onesetting.vbs
-1
0
0
0
0
0
0
0
Note
A computer that contains only one physical network adapter may show 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 Boolean Setting as a StringTo produce more readable output, a minor change in line 5 causes the Boolean settings to be
displayed as True or False rather than -1 or 0, which increases the readability of the script's output.
By echoing "DHCP Enabled: " first and then concatenating the DHCPEnabled property, the script
allows VBScript to "coerce" the Boolean setting into a string format.
Although all VBScript variables are type variant, VBScript automatically coerces (transforms)
variants into appropriate data subtypes depending on the context in which they occur. In this case,
because the script concatenates a variable of subtype Boolean onto a literal string, VBScript
automatically converts the Boolean to its string equivalent.
Scripting Steps
1. Connect to the WMI service.
2. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the
InstancesOf method.
This returns a collection consisting of all the network adapter configurations on the computer.
3. For each network adapter configuration in the collection, use the WSH Echo method to display
the caption "DHCP Enabled:" concatenated with the Boolean property DHCPEnabled.
Listing 2 Onesetting-string.vbs
1
2
3
4
5
6
Set objWMIService = GetObject("winmgmts:")
Set colNicConfig = _
objWMIService.InstancesOf("Win32_NetworkAdapterConfiguration")
For Each objNicConfig In colNicConfig
WScript.Echo "DHCP Enabled: " & objNicConfig.DHCPEnabled
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>onesetting-string.vbs
DHCP Enabled: True
DHCP Enabled: False
DHCP Enabled: False
DHCP Enabled: False
DHCP Enabled: False
DHCP Enabled: False
DHCP Enabled: False
DHCP Enabled: False
Displaying a Setting for Specific Network AdaptersThe previous two examples display the value of the DHCPEnabled property for every network
adapter configuration that WMI can find. 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, may 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 ExecQuery() method of the
SWbemServices object, the object type returned by the GetObject() call on line 1. As a required
parameter, ExecQuery() generally takes a string containing a query in WMI Query Language (WQL),
a dialect of Structured Query Language (SQL). It returns an SWbemObjectSet collection of objects.
Although WQL queries are not case sensitive, putting all WQL keywords in caps is the standard
convention because it makes the script more legible.
The most basic query used by system administrative scripts is "SELECT * FROM classname". This
query returns all instances of the class, and the "*" serves as a wildcard character (as in SQL and
command-line file system specifiers) that returns all the properties of each instance. For example,
"SELECT * FROM Win32_Service" would return all the properties of all the instances of the
Win32_Service class, which would represent all the services currently running on the computer.
In the following script, the WHERE keyword (also part of SQL) enables you to specify limiting
conditions for the query. Here the query "SELECT * FROM Win32_NetworkAdapterConfiguration
WHERE IPEnabled = True" requests all 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 adds 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 3 returns the Index and DHCPEnabled properties for all adapters for which IPEnabled is True.
Scripting Steps
1. Connect to the WMI service.
2. Retrieve specific instances of the Win32_NetworkAdapterConfiguration class with the
ExecQuery method and a query string that filters for those network adapters where the
IPEnabled property is True.
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 and the DHCPEnabled property.
Listing 3 Onesetting-execquery.vbs
1
2
3
4
5
6
7
Set objWMIService = GetObject("winmgmts:")
Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfig
WScript.Echo "Network Adapter: " & objNicConfig.Index
WScript.Echo " DHCP Enabled: " & objNicConfig.DHCPEnabled
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>onesetting-execquery.vbs
Network Adapter: 1
DHCP Enabled: True
Network Adapter: 10
DHCP Enabled: False
In other cases, you may want to restrict the script to running against just a single network adapter
configuration. 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 a
WQL query such as "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = 0."
A simpler way to accomplish the same thing is to use the Get() method of the SWbemServices
object (returned by the GetObject call to the wingmgts: moniker). Get() takes a string containing a
WMI object path as a required parameter and returns an SWbemObject object.
Tip
The following script displays a quirk of WMI: although VBScript, WSH, and WMI typically ignore white
space, within the object path (the string parameter) passed to objWMIService.Get() there can be no
space before or after the equal sign (=) in "Index=0." A space on either side of the equal sign
causes an error.
Scripting Steps
1. Connect to the WMI service.
2. Retrieve a specific instance of the Win32_NetworkAdapterConfiguration class with the Get
method and an object path that specifies an Index property (the key property) equal to 0.
This returns a collection consisting of the network adapter configuration on the computer for
which the index is 0.
3. For this instance, use the WSH Echo method to display the index of the network adapter and
the DHCPEnabled property.
Listing 4 Onesetting-onenic.vbs
1
2
3
4
5
6
7
8
intIndex = 1 ' index of an IP-enabled network adapter
Set objWMIService = GetObject("winmgmts:")
Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapterConfiguration WHERE Index = " & intIndex)
For Each objNicConfig In colNicConfig
WScript.Echo "Network Adapter: " & objNicConfig.Index
WScript.Echo " DHCP Enabled: " & objNicConfig.DHCPEnabled
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>onesetting-onenic.vbs
Network Adapter: 1
DHCP Enabled: True
Displaying Multi-Valued PropertiesBecause 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 be handled in the same way as a single string, Boolean, or
number.
VBScript offers two techniques for transforming arrays into a string format that can be displayed
with WScript.Echo: the Join function and the For Each loop.
Using the VBScript Join functionThe VBScript Join function concatenates or joins together the elements of an array into a single
string that is separated by a character or characters specified in an optional second parameter. If
you do not specify this delimiter, Join uses a single space.
The Join function is necessary because you cannot directly display an array. First, you must divide
the array into its elements or convert the array into a string. Join allows you to control the
formatting of this string. For example, you can use either commas or colons (rather than spaces) to
separate the elements of the array.
Scripting Steps
1. Connect to the WMI service.
2. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the ExecQuery
method and a query string that filters for those network adapters where the IPEnabled property
is True.
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 5 Onesetting-array-join.vbs
1
2
3
4
5
6
7
8
9
10
11
12
Set objWMIService = GetObject("winmgmts:")
Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfig
WScript.Echo "Network Adapter: " & objNicConfig.Index
If Not IsNull(objNicConfig.IPAddress) Then
strIPAddresses = Join(objNicConfig.IPAddress)
Else
strIPAddresses = ""
End If
WScript.Echo " IP Address(es): " & strIPAddresses
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>onesetting-array-join.vbs
Network Adapter: 1
IP Address(es): 0.0.0.0
Network Adapter: 10
IP Address(es): 192.168.1.2
Using For Each ... In ... NextThe For Each loop provides an alternative way to display the elements of an array. This statement
iterates through the array, allowing the script to separately perform an action on each element. In
this case, we merely display the element.
Scripting Steps
1. Connect to the WMI service.
2. Retrieve all the instances of the Win32_NetworkAdapterConfiguration class with the ExecQuery
method and a query string that filters for those network adapters where the IPEnabled property
is True.
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 a For Each loop to iterate through the
IPAddress array, displaying each element with the WSH Echo method.
Listing 6 Onesetting-array-foreach.vbs
1
2
3
4
5
6
7
8
9
10
11
12
Set objWMIService = GetObject("winmgmts:")
Set colNicConfig = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfig
WScript.Echo "Network Adapter: " & objNicConfig.Index
WScript.Echo " IP Address(es):"
If Not IsNull(objNicConfig.IPAddress) Then
For Each strIPAddress In objNicConfig.IPAddress
WScript.Echo " " & strIPAddress
Next
End If
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>onesetting-array-foreach.vbs
Network Adapter: 1
IP Address(es):
0.0.0.0
Network Adapter: 10
IP Address(es):
192.168.1.2
Displaying a Range of Networking PropertiesWhen inventorying network clients, you might often want to gather information about a larger
selection of TCP/IP 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.vbs 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 Steps28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
WScript.Echo " Subnet Mask(s): " & strIPSubnet
If Not IsNull(objNicConfig.DefaultIPGateway) Then
strDefaultIPGateway = Join(objNicConfig.DefaultIPGateway)
Else
strDefaultIPGateway = ""
End If
WScript.Echo " Default Gateways(s): " & strDefaultIPGateway
If Not IsNull(objNicConfig.GatewayCostMetric) Then
strGatewayCostMetric = Join(objNicConfig.GatewayCostMetric)
Else
strGatewayCostMetric = ""
End If
WScript.Echo " Gateway Metric(s): " & strGatewayCostMetric
WScript.Echo " Interface Metric: " & _
objNicConfig.IPConnectionMetric
WScript.Echo " Connection-specific DNS Suffix: " & _
objNicConfig.DNSDomain
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ipsettings.vbs
IP Settings
Network Adapter 1
Intel(R) PRO/1000 MT Network Connection - Packet Scheduler Miniport
DHCP Enabled: True
IP Address(es): 0.0.0.0
Subnet Mask(s):
Default Gateways(s):
Gateway Metric(s):
Interface Metric: 1
Connection-specific DNS Suffix:
Network Adapter 10
3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) - Packet Scheduler
Miniport
DHCP Enabled: False
IP Address(es): 192.168.1.2
Subnet Mask(s): 255.255.255.0
Default Gateways(s):
Gateway Metric(s):
Interface Metric: 20
Connection-specific DNS Suffix:
Win32_NetworkAdapterConfiguration and Win32_NetworkAdapterWin32_NetworkAdapterConfiguration is closely related to Win32_NetworkAdapter, another WMI
class. There is a one-to-one correspondence between instances of the two classes and an implicit
division of labor 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.
Only Win32_NetworkAdapter, however, 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
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 8 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 (".").
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the ExecQuery method to query the Win32_NetworkAdapter class.
This returns a collection consisting of all the network adapters on the computer.
4. For each network adapter in the collection, use the WSH Echo method to display its properties.
5. For those properties that return an array, use the VBScript IsNull() function to check whether
the array is null.
• If the array is not null, use the VBScript Join() function to concatenate the array elements
into a string and display the string.
• If the array is null, display an empty string.
Listing 8 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
31
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNics = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapter")
WScript.Echo VbCrLf & "Network Adapter Settings"
For Each objNic In colNics
WScript.Echo VbCrLf & " Network Adapter (Device ID)" & _
objNic.DeviceID
Wscript.Echo " Index: " & objNic.Index
Wscript.Echo " MAC Address: " & objNic.MACAddress
Wscript.Echo " Adapter Type: " & objNic.AdapterType
Wscript.Echo " Adapter Type Id: " & objNic.AdapterTypeID
Wscript.Echo " Description: " & objNic.Description
Wscript.Echo " Manufacturer: " & objNic.Manufacturer
Wscript.Echo " Name: " & objNic.Name
Wscript.Echo " Product Name: " & objNic.ProductName
Wscript.Echo " Net Connection ID: " & objNic.NetConnectionID
Wscript.Echo " Net Connection Status: " & objNic.NetConnectionStatus
Wscript.Echo " PNP Device ID: " & objNic.PNPDeviceID
Wscript.Echo " Service Name: " & objNic.ServiceName
If Not IsNull(objNic.NetworkAddresses) Then
strNetworkAddresses = Join(objNic.NetworkAddresses)
Else
strNetworkAddresses = ""
End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>nicsettings.vbs
Network Adapter Settings
Network Adapter (Device ID)1
Index: 1
MAC Address: 00:0D:56:15:ED:B7
Adapter Type: Ethernet 802.3
Adapter Type Id: 0
Description: Intel(R) PRO/1000 MT Network Connection
Manufacturer: Intel
Name: Intel(R) PRO/1000 MT Network Connection
Product Name: Intel(R) PRO/1000 MT Network Connection
Net Connection ID: Local Area Connection
Net Connection Status: 7
PNP Device ID: PCI\VEN_8086&DEV_100E&SUBSYS_01511028&REV_02\4&1C660DD6&0&60F0
Service Name: E1000
NetworkAddresses:
Permanent Address:
AutoSense:
Maximum Number Controlled: 0
Speed:
Maximum Speed:
Network Adapter (Device ID)2
Index: 2
MAC Address:
Adapter Type:
Adapter Type Id:
Description: RAS Async Adapter
Manufacturer:
Name: RAS Async Adapter
Product Name: RAS Async Adapter
Net Connection ID:
Net Connection Status:
PNP Device ID:
Service Name:
NetworkAddresses:
Permanent Address:
AutoSense:
Maximum Number Controlled: 0
Speed:
Maximum Speed:
Network Adapter (Device ID)3
Index: 3
MAC Address:
Adapter Type:
Adapter Type Id:
Description: WAN Miniport (L2TP)
Manufacturer: Microsoft
Name: WAN Miniport (L2TP)
Product Name: WAN Miniport (L2TP)
Net Connection ID:
Net Connection Status:
PNP Device ID: ROOT\MS_L2TPMINIPORT\0000
Service Name: Rasl2tp
NetworkAddresses:
Permanent Address:
AutoSense:
Maximum Number Controlled: 0
Speed:
Maximum Speed:
Network Adapter (Device ID)6
Index: 6
MAC Address:
Adapter Type:
Adapter Type Id:
Description: Direct Parallel
Manufacturer: Microsoft
Name: Direct Parallel
Product Name: Direct Parallel
Net Connection ID:
Net Connection Status:
PNP Device ID: ROOT\MS_PTIMINIPORT\0000
Service Name: Raspti
NetworkAddresses:
Permanent Address:
AutoSense:
Maximum Number Controlled: 0
Speed:
Maximum Speed:
Network Adapter (Device ID)8
Index: 8
MAC Address: 00:0D:56:15:ED:B7
Adapter Type: Ethernet 802.3
Adapter Type Id: 0
Description: Packet Scheduler Miniport
Manufacturer: Microsoft
Name: Packet Scheduler Miniport
Product Name: Packet Scheduler Miniport
Net Connection ID:
Net Connection Status:
PNP Device ID: ROOT\MS_PSCHEDMP\0000
Service Name: PSched
NetworkAddresses:
Permanent Address:
AutoSense:
Maximum Number Controlled: 0
Speed:
Maximum Speed:
Network Adapter (Device ID)10
Index: 10
MAC Address: 00:0A:5E:3D:E3:70
Adapter Type: Ethernet 802.3
Adapter Type Id: 0
Description: 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX)
Manufacturer: 3Com
Name: 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX)
Product Name: 3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX)
Net Connection ID: Local Area Connection 2
Net Connection Status: 2
PNP Device ID: PCI\VEN_10B7&DEV_9200&SUBSYS_100010B7&REV_78\4&1C660DD6&0&40F0
Service Name: EL90Xbc
NetworkAddresses:
Permanent Address:
AutoSense:
Maximum Number Controlled: 0
Speed:
Maximum Speed:
Associating the Network Connections Name with MAC and IP Addresses Using Two ClassesFor 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
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). 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 PropertyWin32_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.
Getncmacip.vbs 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. The script gets properties
from corresponding instances of Win32_NetworkAdapter and Win32_NetworkAdapterConfiguration
by using the direct correlation between Win32_NetworkAdapter.DeviceID and
Win32_NetworkAdapterConfiguration.Index.
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. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. 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.
4. Iterate through each network adapter configuration in the collection, performing the following
steps.
5. Use the Get method of the objWMIService object to fetch the instance of
Win32_NetworkAdapter whose DeviceID property equals the Index property of
Win32_NetworkAdapterConfiguration.
6. Display the AdapterType and NetConnectionID properties of the current instance of
Win32_NetworkAdapter.
If an error occurs, the NetConnectionID property does not exist (this property is new to
Windows XP and Windows Server 2003); so switch back to displaying the Index property of
Win32_NetworkAdapterConfiguration to identify the current network adapter.
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 Getncmacip.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "MAC & IP Addresses & Subnet Masks"
For Each objNicConfig In colNicConfigs
Set objNic = objWMIService.Get _
("Win32_NetworkAdapter.DeviceID=" & objNicConfig.Index)
WScript.Echo VbCrLf & " " & objNic.AdapterType & " " & _
objNic.NetConnectionID
If Err Then
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
End If
WScript.Echo " " & objNicConfig.Description & VbCrLf
WScript.Echo " MAC Address:" & VbCrLf & _
" " & objNic.MACAddress
WScript.Echo " IP Address(es):"
For Each strIPAddress In objNicConfig.IPAddress
WScript.Echo " " & strIPAddress
Next
WScript.Echo " Subnet Mask(s):"
For Each strIPSubnet In objNicConfig.IPSubnet
WScript.Echo " " & strIPSubnet
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>getncmacip.vbs
MAC & IP Addresses & Subnet Masks
Ethernet 802.3 Local Area Connection
Intel(R) PRO/1000 MT Network Connection - Packet Scheduler Miniport
MAC Address:
00:0D:56:15:ED:B7
IP Address(es):
0.0.0.0
Subnet Mask(s):
Ethernet 802.3 Local Area Connection 2
3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) - Packet Scheduler
Miniport
MAC Address:
00:0A:5E:3D:E3:70
IP Address(es):
192.168.1.2
Subnet Mask(s):
255.255.255.0
Using Association Classes to Retrieve Correlated DataAnother way to get data from related instances of Win32_NetworkAdapterConfiguration and
Win32_NetworkAdapter is to use the association class, Win32_NetworkAdapterSetting. In this case,
the properties to be correlated are the NetConnectionID and MACAddress properties of
Win32_NetworkAdapter and the IPAddress and IPSubnet properties of
Win32_NetworkAdapterConfiguration.
Figure 6 illustrates how the Win32_NetworkAdapterSetting association class is used to obtain data
from related instances of these two classes. This example uses an ASSOCIATORS OF query with the
ExecQuery method of SWbemServices to associate properties from the two classes. ASSOCIATORS
OF is a keyword of WMI Query Language (WQL).
Figure 6 Correlating Data by Using Win32_NetworkAdapterSetting
See full-sized image
Associating the Network Connections Name with IP Addresses Using an Association ClassGetncmacip-assoc.vbs displays the network connection name (called an index number on clients
that run an operating system older than Windows XP), MAC address, IP addresses, and subnet
masks for IP-enabled network interfaces. It uses the Win32_NetworkAdapterSetting association class
to correlate properties from Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter. A
network adapter configuration can have more than one IP address and subnet.
Scripting Steps
Listing 10 retrieves the TCP/IP network client properties on a single computer.
1. Create a variable to specify the computer name.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. 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.
4. For each network adapter configuration in the collection, use the ExecQuery method to query
the Win32_NetworkAdapterConfiguration class with an ASSOCIATORS OF query. The query
returns a collection of instances of Win32_NetworkAdapter.
An ASSOCIATORS OF query uses the Win32_NetworkAdapterSetting association class to
correlate the instances of Win32_NetworkAdapterConfiguration (identified by the Index
property) with the corresponding instances of the associated class, Win32_NetworkAdapter.
5. Iterate through the collection of instances of Win32_NetworkAdapter, displaying the
AdapterType, NetConnectionID, and MACAddress properties.
If an error occurs when displaying the NetConnectionID property, display instead the Index of
the corresponding instance of Win32_NetworkAdapterConfiguration.
6. Display the IPAddress and IPSubnet properties for the instance of
Win32_NetworkAdapterConfiguration associated with the current instance of
Win32_NetworkAdapter.
Listing 10 Getncmacip-assoc.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "MAC & IP Addresses & Subnet Masks"
For Each objNicConfig In colNicConfigs
Set colNics = objWMIService.ExecQuery _
("ASSOCIATORS OF " & "{Win32_NetworkAdapterConfiguration.Index='" & _
objNicConfig.Index & "'}" & _
" WHERE AssocClass=Win32_NetworkAdapterSetting")
For Each objNic in colNics
WScript.Echo VbCrLf & " " & objNic.AdapterType & " " & _
objNic.NetConnectionID
If Err Then
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
End If
WScript.Echo " " & objNicConfig.Description & VbCrLf
WScript.Echo " MAC Address:" & VbCrLf & _
" " & objNic.MACAddress
WScript.Echo " IP Address(es):"
For Each strIPAddress In objNicConfig.IPAddress
WScript.Echo " " & strIPAddress
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>getncmacip-assoc.vbs
MAC & IP Addresses & Subnet Masks
Ethernet 802.3 Local Area Connection
Intel(R) PRO/1000 MT Network Connection - Packet Scheduler Miniport
MAC Address:
00:0D:56:15:ED:B7
IP Address(es):
0.0.0.0
Subnet Mask(s):
Ethernet 802.3 Local Area Connection 2
3Com EtherLink 10/100 PCI For Complete PC Management NIC (3C905C-TX) - Packet Scheduler
Miniport
MAC Address:
00:0A:5E:3D:E3:70
IP Address(es):
192.168.1.2
Subnet Mask(s):
255.255.255.0
Displaying Settings Filtered for Network Connections NameNow that you know how to use a single script to retrieve related properties from
Win32_NetworkAdapterConfiguration and Win32_NetworkAdapter, here is another way you might
want to use this capability. If you need information from only one network adapter, you could
connect to it by using its name under Network Connections — a more mnemonic identifier than the
index number — and retrieve a setting from that network adapter. You can do this by using the
NetConnectionID property of Win32_NetworkAdapter.
The NetConnectionID property is available only on Windows XP and Windows Server 2003. If the
property is not found, the script generates a run-time error, which is handled by checking the
VBScript Err object. If the Err object's default property, Number, is not 0, an error has occurred; in
response, the script displays an error message and ends.
Scripting Steps
Listing 11 retrieves the TCP/IP network client properties on a single computer.
1. Create a variable to specify the computer name.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the ExecQuery method to query the Win32_NetworkAdapter class, filtering the WQL query
with a WHERE clause for a specific NetConnectionID.
This returns a collection of one instance representing the network adapter with that particular
NetConnectionID.
4. Check that the NetConnectionID was found. If it was, proceed with the tasks of the script.
5. For each network adapter in the collection, correlate each network adaptor configuration with a
network adapter by using an ASSOCIATORS OF query. To do this, you must use the DeviceID
property of Win32_NetworkAdapter, which is the key property for this class (lines 12–15).
6. For each network adapter and associated configuration, display the adapter type and IP
addresses.
7. If the specific NetConnectionID was not found, display a message.
Listing 11 Getncip.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
On Error Resume Next
strComputer = "."
strNetConn = "Local Area Connection"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNics = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapter WHERE NetConnectionID = '" & strNetConn & "'")
If colNics.Count > 0 Then
For Each objNic in colNics
Set colNicConfigs = objWMIService.ExecQuery ("ASSOCIATORS OF " & _
"{Win32_NetworkAdapter.DeviceID='" & objNic.DeviceID & "'}" & _
" WHERE AssocClass=Win32_NetworkAdapterSetting")
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & " " & objNic.AdapterType & " " & _
objNic.NetConnectionID
If Not IsNull(objNicConfig.IPAddress) Then
For Each strIPAddress in objNicConfig.IPAddress
Wscript.Echo " IP Address: " & strIPAddress
Next
End If
Next
Next
Else
WScript.Echo "Unable to find NetconnectID named '" & strNetConn & "'." & _
VbCrLf & "If Windows 2000 or earlier, NetConnectionID property unavailable."
End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>getncip.vbs
Ethernet 802.3 Local Area Connection
IP Address: 192.168.0.213
Top of page
Displaying Expanded IP Configuration DataIn 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
See full-sized image
Using Ipconfig.exe to Display Expanded Configuration DataYou 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
See full-sized image
Using a Script to Display Expanded Configuration DataWMI 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
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
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 page
Tools for Basic TCP/IP Networking on ClientsThe 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 AvailableArp.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
Tool Where AvailableNetset.exe Windows 2000 Resource Kit
Netsh.exe Windows operating systems
Netstat.exe Windows operating systems
Networkprotocol.vbs Windows 2000 Resource Kit
Ping.exe Windows 2000 Resource Kit
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
Technology Object or Class Notes/Where AvailableWSH WshController
WshNetwork
WshShell
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
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 SubkeysHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dhcp
Registry SubkeysHKEY_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
Automating TCP/IP Networking on ClientsPart 3: Scripting Remote Network Management
Published: July 19, 2004This section illustrates how to write scripts to perform tasks on remote computers. It also highlights
good scripting practices to follow when you run scripts remotely.
The value of scripting with VBScript, WSH, and WMI does not become fully apparent until you try to
run scripts over a network on multiple computers. The techniques involved are not difficult, because
remote operations are an intrinsic part of WMI. You can use all the techniques described in the
previous section, “Scripting Basic TCP/IP Networking on Clients,” on one or more remote computers
by making a few relatively simple modifications.
For more information about these and related techniques, see "Tales from the Script - November
2002: Running WMI Scripts Against Multiple Computers" at http://go.microsoft.com/fwlink/?
LinkId=24786.
Note
The WshController object of Windows Script Host provides another way to run scripts against remote
computers. However, the WshController object is not included here because WMI provides simpler
and more powerful ways to accomplish the scripting tasks discussed in this paper.
This section provides information about managing remote computers, including scripting steps and
sample scripts for these topics:
• Connecting to a remote computer and retrieving basic settings.
• Connecting to a group of computers on a network.
• Recording the data that you collect from network computers.
On This Page
Retrieving Basic Settings from a Remote Computer
Connecting to Groups of Computers on a Network
Reporting Data from Multiple Computers
Tools for Scripting Remote Network Management
Retrieving Basic Settings from a Remote ComputerMost system administrators need to manage remote computers on their network and can use
scripts to great advantage for this purpose. The previous section discussed scripting techniques for
retrieving and displaying settings on a local computer; this section shows how to modify those
scripts for use on a remote computer. By using the techniques explained in the next two topics, you
can use WMI to connect to a remote computer, and then retrieve and display the settings for that
computer.
Using WMI to Connect to a Remote ComputerTo use WMI to connect to a remote computer over the network, simply assign the name of the
remote computer to the host variable used in the WMI object path. WMI handles the details of
connecting to remote computers.
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer)
In the preceding example, WMI connects to the local computer. The period or dot character, (.)
represents the local computer in WMI object paths. It connects to the default WMI namespace —
typically root\cimv2 — by using the default impersonation level, "impersonate."
To connect to WMI on a remote computer, replace "." with the name of the remote computer:
strComputer = "client1"
Set objWMIService = GetObject("winmgmts:\\" & strComputer)
As on local computers, you must have sufficient administrative privileges on the remote computer
to perform the actions that the script takes.
For more information about connecting to WMI, see the topic "Connecting to WMI Using the WMI
Moniker," which is in the "WMI Scripting Primer" chapter of the Windows 2000 Scripting Guide at
http://go.microsoft.com/fwlink/?LinkId=29993.
Getting the IP Addresses and Subnet Masks of a Remote ComputerThe following script shows how to retrieve a couple of TCP/IP client settings from a remote
computer. The code is almost identical to the code used in scripts that connect to WMI on the local
computer; the only difference is that the name of an accessible remote computer is assigned to the
strComputer variable.
Scripting Steps
Listing 13 retrieves the IPAddress and IPSubnet properties (both arrays) for each network adapter
configuration on a remote computer.
1. Invoke On Error Resume Next, which is the error-handling mechanism of VBScript.
2. Create a variable to specify the remote computer name. This code is similar to that used in
most scripts in this paper that run locally. However, the script assigns the string “client1” (the
name of a remote computer) — in place of "." (the local computer) — to strComputer.
To run this script, replace "client1" on line 3 with the name of an accessible remote computer
on which you have administrative privileges.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.” Here strComputer is concatenated into the object path so that the
script binds to the \root\cimv2 namespace on the remote computer. The impersonation level
and namespace are specified explicitly.
4. 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.
5. For each network adapter configuration in the collection, retrieve the index number,
description, IP addresses, and subnet masks.
Listing 13 Getip.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
On Error Resume Next
strComputer = "client1"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "Computer Name: " & strComputer
WScript.Echo " IP Addresses & Subnet Masks"
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
WScript.Echo " " & objNicConfig.Description & VbCrLf
WScript.Echo " IP Address(es):"
For Each strIPAddress In objNicConfig.IPAddress
WScript.Echo " " & strIPAddress
Next
WScript.Echo " Subnet Mask(s):"
For Each strIPSubnet In objNicConfig.IPSubnet
WScript.Echo " " & strIPSubnet
Next
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>getip.vbs
Computer Name: client1
IP Addresses & Subnet Masks
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packet Scheduler
Miniport
IP Address(es):
192.168.0.11
Subnet Mask(s):
255.255.255.0
Top of page
Connecting to Groups of Computers on a NetworkWhen you run WMI-based scripts to perform networking tasks on groups of computers, you can
typically accomplish those tasks more efficiently and flexibly than with most Windows interface or
command-line tools.
Whenever you must connect to remote computers, there are certain precautions you should use in
your scripts. These precautions can help you avoid wasting time trying to run a script on computers
that are unreachable or on which WMI is unavailable. WMI is not installed by default on operating
systems before Windows 2000 and Windows Millennium Edition.
When you are connecting to remote computers, it is helpful to first check whether you can reach
each computer over the network. The command-line tool Ping.exe is one traditional way of doing
this. On Windows XP and later versions of Windows, WMI offers a new Win32_PingStatus class that
closely duplicates the functionality of Ping.exe.
Because there is a greater chance of encountering problems when running a script on remote
computers, it is often a good idea to use the error-handling mechanism in VBScript, which is called
On Error Resume Next, so that network or remote problems do not crash the script. If the script
encounters an error on one computer, this allows it to continue running on other computers.
You can also capture the error and then display or log it. For more information about error handling,
see "Error Handling" in the "VBScript Primer" section of the Windows 2000 Scripting Guide at
http://go.microsoft.com/fwlink/?LinkId=27641.
This section provides scripting steps and sample scripts on these topics:
• Pinging network hosts before trying to run scripts on them.
• Handling errors with VBScript.
• Using an array to input a list of network hosts.
• Obtaining the IP addresses and subnet masks of a group of remote computers.
• Using a text file with a list of hosts as input.
• Connecting to a subnet or range of IP addresses.
• Other ways to provide input to scripts.
Pinging Network Hosts Before Trying to Run Scripts on ThemIt is good practice to connect to each remote host to ensure that it is reachable before trying to do
anything on it. If all the computers you have to ping are running Windows XP or Windows
Server 2003, you can use the new WMI class Win32_PingStatus. Win32_PingStatus returns an object
with 24 properties that supply extensive details about the ping packets that the class sends.
If earlier operating systems are involved, the TCP/IP command-line tool Ping.exe is the standard way
to check connectivity. You can run Ping and command-line parameters with the Exec() method of
the WshShell object. Ping sends a configurable number of ICMP broadcast packets to the host name
or IP address and listens for replies. The script can parse the responses on STDOUT for the "reply
from" string, which occurs only if the computer has responded to the ping.
Note
The ping succeeds only if the routing infrastructure forwards the ping messages and the destination
is not using a firewall that prevents the ping messages from being received.
Pinging a Single Network Host by Running Ping.exe from a ScriptTo determine whether a computer is accessible on the network before trying to connect to WMI and
perform a task on it, a script can use WSH to call Ping.exe. VBScript provides string-handling
functions that enable the script to parse the resulting StdOut stream to see if the remote computer
responded and act accordingly.
Scripting Steps
Listing 14 illustrates how to run Ping.exe with the WshShell Exec() method.
1. Invoke the VBScript error-handling mechanism, On Error Resume Next.
2. Create a variable to specify the remote computer name.
This script uses almost the same code used in most scripts in this paper. Here, though, it
assigns “client1” (the name of the remote computer) to strComputer instead of “.” (the WMI
name for the local computer). WMI also accepts IP addresses as the identifier of the remote
computer. To run this script, replace "client1" with the name or IP address of an accessible
remote computer on which you have administrative privileges.
3. Create a WshShell object and assign it to objShell.
4. Run the Exec method of objShell, passing it parameters that call for sending two echo requests,
with a wait of 1000 milliseconds (one second) for each response, to the target computer.
Assign the resulting object to objExec.
5. Read the entire StdOut stream produced by the objExec object, convert it to lowercase to avoid
case confusion, and assign the stream to the variable strPingResults.
6. Call the InStr function of VBScript, which searches the first parameter, the string of results from
the Ping for any occurrences of the second parameter, the literal string "reply from." If the
literal is found, then Ping succeeded, and the target computer responded.
InStr returns the character position in the first string in which the second string is found; if it is
not found, InStr returns 0.
The If...Then statement interprets any number except zero as True for its condition, the script
then executes the lines of code that follow before Else (8–15). Because the target computer
has responded, the script can connect to WMI on the target and display its name. This is just a
simple example: after the script connects to the target computer, it can perform any set of WMI
and ADSI tasks.
7. If InStr does not find the string "reply from" and returns 0, then the remote computer has not
responded to the Ping. In this case, the If...Then statement transfers script execution to the
Else statement on line 16, and the script displays a message that the target did not respond to
the ping. The script does not try to connect to WMI or perform the task on the remote computer
because doing so would result in an error.
Listing 15 Ping.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
On Error Resume Next
strTarget = "192.168.0.1" 'IP address or hostname
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "reply from") Then
WScript.Echo strTarget & " responded to ping."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strTarget & "\root\cimv2")
Set colCompSystems = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_ComputerSystem")
For Each objCompSystem In colCompSystems
WScript.Echo "Host Name: " & LCase(objCompSystem.Name)
Next
Else
WScript.Echo strTarget & " did not respond to ping."
End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ping.vbs
192.168.0.1 responded to ping.
Host Name: server1
Pinging Multiple Network Hosts by Running Ping.exe from a ScriptWith a few more lines of code, a script can ping multiple computers one at a time before attempting
to perform a task on each. The computer names are passed to the script in the form of an array,
which is a simple way to accomplish this. However, the computer names can also be retrieved from
a text file, spreadsheet, or database; or they can be enumerated from an Active Directory
organizational unit (OU) by using only a little more code.
Scripting Steps
Listing 15 illustrates how to run Ping.exe with the WshShell Exec() method against multiple
computers.
1. Invoke On Error Resume Next, which is the error-handling mechanism for VBScript.
2. Create an array with the VBScript Array function and add as elements the names or IP
addresses of accessible computers on the network. The WMI service accepts both host names
and IP addresses in the object path on line 12. Assign the array to the variable arrTargets.
3. Use a For Each loop to iterate through each element in the array. For each computer name,
perform the same steps performed on the remote computer in the previous example, Ping.vbs.
Listing 15 Ping-multi.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
On Error Resume Next
arrTargets = Array("192.168.0.1", "192.168.0.11", "192.168.0.12", _
"192.168.0.13")
For Each strTarget In arrTargets
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "reply from") Then
WScript.Echo VbCrLf & strTarget & " responded to ping."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strTarget & "\root\cimv2")
Set colCompSystems = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_ComputerSystem")
For Each objCompSystem In colCompSystems
WScript.Echo "Host Name: " & LCase(objCompSystem.Name)
Next
Else
WScript.Echo VbCrLf & strTarget & " did not respond to ping."
End If
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ping-multi.vbs
192.168.0.1 responded to ping.
Host Name: server1
192.168.0.11 responded to ping.
Host Name: client1
192.168.0.12 responded to ping.
Host Name: client2
192.168.0.13 did not respond to ping.
Pinging a Single Network Host by Using the Win32_PingStatus ClassOn Windows XP and Windows Server 2003, the new WMI class Win32_PingStatus can return more
details of the ping operation than those provided by Ping.exe. However, you can only use this WMI
class on a network that is running just these two operating systems.
In such a situation, this script can serve as a template for testing a single remote computer for
connectivity with a ping before attempting to connect to WMI and perform tasks on it.
The StatusCode property of Win32_PingStatus returns the status codes shown in Table 6. Their data
type is uint32 and they are read-only. To make this script more user-friendly, you can translate the
status codes into the descriptive string that appears in Table 6.
Table 6 Win32_Pingstatus Status Codes
Value Description0 Success
11001 Buffer Too Small
11002 Destination Net Unreachable
11003 Destination Host Unreachable
11004 Destination Protocol Unreachable
11005 Destination Port Unreachable
11006 No Resources
11007 Bad Option
11008 Hardware Error
11009 Packet Too Big
11010 Request Timed Out
11011 Bad Request
11012 Bad Route
11013 TimeToLive Expired Transit
11014 TimeToLive Expired Reassembly
11015 Parameter Problem
11016 Source Quench
11017 Option Too Big
11018 Bad Destination
11032 Negotiating IPSEC
11050 General Failure
Scripting Steps
Listing 16 illustrates how to use the Win32_PingStatus class to test the connectivity of a remote
computer and display information about the ping results that the properties of this class can return.
1. Invoke the VBScript error-handling mechanism, On Error Resume Next.
2. Create a variable to specify the name of the computer that runs the script.
3. Create a variable to specify the name of the target computer to be pinged.
4. Connect to the WMI service on the computer where you run the script.
This example runs the script on the local computer (".") and targets the local loopback address
("127.0.0.1"), but you can run this script on a remote computer and ping another remote
computer.
5. Call the ExecQuery method of the WMI service object, passing it a WQL query that requests all
properties (*) from the instance of Win32_PingStatus where the address is that of the target
computer. Assign the resulting collection of instances (in this example, just one instance
results) to the variable colPings.
The Win32_PingStatus is unusual within WMI in that you do not call a method to perform
actions with it. Rather, you simply query the class, filtering with WHERE for the instance where
the value of Address, which is one of the key properties, is the name or IP address of the target
computer. You can also filter for several other key properties to configure the ping. By running
such a query, the script initiates the ping operation.
6. If no error occurs in querying the Win32_PingStatus class, iterate through the collection of ping
objects (there is only one by nature of the query).
7. If no error occurs in iterating through the collection of ping objects, check the status code
returned by the ping object.
8. If the status code is 0, which indicates that the target responded to the ping, display several of
the properties returned by the ping object.
9. If an error occurs, either in querying the Win32_PingStatus class or in iterating through the
collection of ping objects, clear the status code and display the status code description.
Listing 16 Pingstatus.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
On Error Resume Next
strComputer = "."
strTarget = " client1" 'IP address or hostname
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colPings = objWMIService.ExecQuery _
("Select * From Win32_PingStatus where Address = '" & strTarget & "'")
If Err = 0 Then
Err.Clear
For Each objPing in colPings
If Err = 0 Then
Err.Clear
If objPing.StatusCode = 0 Then
Wscript.Echo strTarget & " responded to ping."
Wscript.Echo "Responding Address: " & objPing.ProtocolAddress
Wscript.Echo "Responding Name: " & objPing.ProtocolAddressResolved
Wscript.Echo "Bytes Sent: " & objPing.BufferSize
Wscript.Echo "Time: " & objPing.ResponseTime & " ms"
Wscript.Echo "TTL: " & objPing.ResponseTimeToLive & " seconds"
Else
WScript.Echo strTarget & " did not respond to ping."
WScript.Echo "Status Code: " & objPing.StatusCode
End If
Else
Err.Clear
WScript.Echo "Unable to call Win32_PingStatus on " & strComputer & "."
End If
Next
Else
Err.Clear
When you use Cscript.exe to run this script, output similar to the following is displayed in the command window: Automating TCP/IP Networking on ClientsPart 4: Scripting IP Address Allocation on Clients
Published: July 12, 2004At the heart of TCP/IP networking is the allocation of IP addresses. If your network uses Dynamic
Host Configuration Protocol (DHCP), you are already using a form of automation to manage this
critical function.
In the early days of TCP/IP networking, administrators assigned IP addresses manually. As
networks grew and became more complex, this became impractical. Early efforts to automate
this function, such as Reverse Address Resolution Protocol (RARP) and Bootstrap Protocol
(BOOTP), still required considerable manual configuration. DHCP was developed to replace them
and extend their functionality into a client/server protocol capable of managing an IP address
pool and related client configuration parameters with much less administrative intervention.
Today, on most networks of any size, DHCP is the default way to automate the management of IP
address configuration. Even when your network uses DHCP, though, you may still need to use
static IP addresses in certain cases, such as exclusions. In addition, some smaller or older
networks may use only static IP addresses.
DHCP servers and clients also interact with other TCP/IP components in significant ways. For
example, when using DNS dynamic update, DHCP clients and servers update DNS servers with
changes in IP addresses to ensure that name resolution remains accurate as IP address leases
are released and renewed.
Here, as with most TCP/IP settings, you can manually make changes on a local computer by using
the Windows interface. For example, as Figure 9 illustrates, you can configure DHCP settings on
the IP Settings tab of the Advanced TCP/IP Settings dialog box.
Figure 9 Configuring DHCP Setting by Using the Windows Interface
See full-sized image
As previously mentioned, you can also use the command-line tool Ipconfig.exe to retrieve DHCP
client settings, release and renew leases, and perform other DHCP client tasks. For remote and
multiple clients, though, as well as for complex local tasks that risk manual errors, scripting may
be a more efficient alternative.
This section discusses how to script the management of IP address allocation by using both DHCP
and static addressing. This paper covers only how to configure clients, although in some cases,
the changes on clients also require changes on the DHCP servers. Management of DHCP servers
is not covered in this paper.
On This Page
Managing DHCP on Clients
Managing Static IP Addresses
Scenario: Allocating IP Addresses on a Subnet
Scenario: Switching Between a Static IP Address and DHCP
Tools for IP Address Allocation on Clients
Managing DHCP on Clients
Although DHCP is already a form of automation, scripting can help you automate the
configuration of groups of clients to take advantage of DHCP. Through the properties and
methods provided by the WMI class Win32_NetworkAdapterConfiguration, you can enumerate
DHCP settings, enable or disable DHCP, and renew or release releases.
Table 9 describes the Win32_NetworkAdapterConfiguration properties that you can use for IP
address allocation.
Table 9 Win32_NetworkAdapterConfiguration IP Address Allocation Properties
Property Type DescriptionDefaultIPGateway String arrayArray of IP addresses of default gateways that the computer
system uses.
DHCPEnabled Boolean If TRUE, the DHCP server automatically assigns an IP address to
the computer system when establishing a network connection.
DHCPLeaseExpires Datetime Expiration date and time for a leased IP address that was
assigned to the computer by the DHCP server.
DHCPLeaseObtained Datetime The date and time that the lease was obtained for the IP address
assigned to the computer by the DHCP server.
DHCPServer String IP address of the DHCP server.
GatewayCostMetric Uint16 Array of integer cost metric values (ranging from 1 to 9999) to be
used in calculating the fastest, most reliable, or least expensive
routes. This argument has a one-to-one correspondence with the
DefaultIPGateway property.
IPConnectionMetric
(New in Windows XP)
Uint32 Cost of using the configured routes for the IP bound adapter and
is the weighted value for those routes in the IP routing table. If
there are multiple routes to a destination in the IP routing table,
the route with the lowest metric is used. The default value is 1.
IPAddress String Array of all of the IP addresses associated with the current
network adapter.
IPSubnet String Array of all the subnet masks associated with the current network
adapter.
All the properties in the previous table are read-only. The types uint16 and uint32 are unsigned
integer types that are used by strongly-typed programming languages; VBScript effectively treats
them as integers.
Table 10 describes the Win32_NetworkAdapterConfiguration methods that you can use for IP
address allocation.
Table 10 Win32_NetworkAdapterConfiguration IP Address Allocation Methods
Method Parameters DescriptionEnableDHCP None Enables DHCP for service with this network adapter.
DHCP allows IP addresses to be dynamically allocated.
EnableStatic IPAddress – array of
strings
SubnetMask – array
of strings
Enables static TCP/IP addressing for the target network
adapter. As a result, DHCP for this network adapter is
disabled.
ReleaseDHCPLease None Releases the IP address bound to a specific DHCP-
enabled network adapter.
Caution If DHCP is enabled on the local computer, this
option disables TCP/IP on the specific network adapter.
Method Parameters DescriptionUnless you have an alternate path to the target system,
that is, another TCP/IP bound network adapter, all
TCP/IP communications will be lost.
ReleaseDHCPLeaseAll None Static method. Releases the IP addresses bound to all
DHCP-enabled network adapters.
Caution If DHCP is enabled on the local computer, this
option terminates all DHCP TCP/IP connections.
RenewDHCPLease None Renews the IP address on specific DHCP-enabled
network adapters. The lease for the IP address assigned
by a DHCP server has an expiration date that the client
must renew if it intends to continue use of the assigned
IP address.
RenewDHCPLeaseAll None Static method. Renews the IP addresses on all DHCP-
enabled network adapters. The lease for the IP address
assigned by a DHCP server has an expiration date that
the client must renew if it intends to continue use of
the assigned IP address.
SetGateways DefaultIPGateway –
array of strings
GatewayCostMetric
– unit16
Specifies a list of gateways for routing packets to a
subnet that is different from the subnet that the
network adapter is connected to. This method only
works when the network adapter is in static IP mode.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that some problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
Displaying DHCP Client InformationWhen you are working with a technology like DHCP, the first step in scripting is usually to
determine the current configuration of settings relevant to it. This is the approach that is taken in
this section and in those that follow.
Win32_NetworkAdapterConfiguration provides per-adapter properties that show whether DHCP is
enabled; the IP address of the DHCP server; the date and time when the lease was obtained and
when it will expire; and the client IP addresses and subnet masks (network adapters can have
more than one of each).
Because WMI returns dates and times in a format that is not designed for easy reading,
displaying lease dates and times requires converting the WMI date and time format to a more
user-friendly one.
The following script displays IP address allocation settings for a network client by using the
following properties of Win32_NetworkAdapterConfiguration: DHCPEnabled, DHCPServer,
DHCPLeaseObtained, DHCPLeaseExpires, IPAddress, and IPSubnet. The script displays settings for
DHCPServer, DHCPLeaseObtained, and DHCPLeaseExpires only if DHCP is enabled.
Rather than directly displaying the settings with the WSH WScript.Echo method, the script assigns
them to a string and displays them after they have been collected. Then, after verifying with an If
... Then clause that DHCPEnabled is True, the script displays the subordinate settings.
Two of the settings displayed by Dhcpsettings.vbs, DHCPLeaseObtained and DHCPLeaseExpires,
are returned as a DATETIME value. If you display the raw value, it look likes this:
20021201000230.000000+000
The first four digits represent the year, the next two the month, the next two the day, then hours,
minutes, seconds, and so on. You can figure out what it means — although it is not quick and
easy to read.
Windows XP and Windows Server 2003 have added a new SWbemDateTime object to the WMI
Scripting API. This object makes it easier to parse and convert datetime values if all your clients
are running Windows XP and Windows Server 2003.
However, if not all your network hosts are running Windows XP or Windows Server 2003, a more
convenient and less complicated solution is to parse datetime values into a readable format by
using the string manipulation capabilities of VBScript.
In this script, to convert the datetime value into something more readable, Dhcpsettings calls a
function, WMIDateToString(), and passes it the datetime value as a parameter. The function
transforms the value with the VBScript built-in Mid() and Left() string functions. It then calls the
VBScript CDate() function to cast the variant value (the type of all VBScript variables) as a sub-
type Date, and returns the formatted date to the main body of the script.
For more information about the WMI DATETIME format, see "Setting the Time on One Computer
by Using WMI" later in this document.
Scripting Steps
Listing 19 displays the DHCP settings for each network adapter configuration on a computer.
1. Create a variable and assign the name of a computer to it. For the local computer, simply
specify "." as the computer name. To run this script remotely, specify the name of an
accessible remote computer on your network on which you have administrative privileges.
The name can be in the form of either a host name or an IP address.
2. Use a GetObject call to connect to the WMI namespace root\cimv2 on the specified
computer, and set the impersonation level to “impersonate.”
3. 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.
4. For each network adapter configuration in the collection, perform the following tasks.
5. Call the Get method on objWMIService to obtain an object reference to the instance of
Win32_NetworkAdapter whose DeviceID property is equal to the Index property of the
current instance of Win32_NetworkAdapterConfiguration.
6. Get the value of the DNSHostName property of Win32_NetworkAdapterConfiguration and
assign it to a variable.
7. Get the value of the NetConnectionID property of Win32_NetworkAdapter and assign it to a
variable. If this raises an error, use the Index property of
Win32_NetworkAdapterConfiguration instead.
8. Get the DHCPEnabled property of Win32_NetworkAdapterConfiguration and assign it to a
variable.
9. If the DHCPEnabled property is True, meaning that DHCP is enabled on the current network
adapter, get the other properties related to IP address allocation and assign them to
variables.
10. For the DHCPLeaseObtained and DHCPLeaseExpires properties of
Win32_NetworkAdapterConfiguration, pass their values as a parameter to the
WMIDateToString function. This function converts the DATETIME format returned by these
two properties into more readable strings.
11. Concatenate the variables containing the values of the properties with explanatory labels
into a long string and display the string with WScript.Echo.
Listing 19 Dhcpsettings.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
strDNSHostName = objNicConfig.DNSHostName
strIndex = objNicConfig.Index
strDescription = objNicConfig.Description
blnDHCPEnabled = objNicConfig.DHCPEnabled
If blnDHCPEnabled Then
strDHCPServer = objNicConfig.DHCPServer
dtmRawLeaseObtainedDate = objNicConfig.DHCPLeaseObtained
strDHCPLeaseObtained = WMIDateToString(dtmRawLeaseObtainedDate)
dtmRawLeaseExpiresDate = objNicConfig.DHCPLeaseExpires
strDHCPLeaseExpires = WMIDateToString(dtmRawLeaseExpiresDate)
End If
strDHCPSettings = strDHCPSettings & VbCrLf & VbCrLf & _
" Network Adapter " & strIndex & VbCrLf & _
" " & strDescription & VbCrLf & VbCrLf & _
" DHCP Enabled: " & blnDHCPEnabled
If blnDHCPEnabled Then
strDHCPSettings = strDHCPSettings & VbCrLf & _
" DHCP Server: " & strDHCPServer & VbCrLf & _
" DHCP Lease Obtained: " & strDHCPLeaseObtained & VbCrLf & _
" DHCP Lease Expires: " & strDHCPLeaseExpires
End If
Automating TCP/IP Networking on ClientsPart 5: Scripting DNS on Clients
Published: July 12, 2004Domain Name System (DNS) is the primary mechanism for name resolution on most TCP/IP
networks, and the default name-resolution protocol for Windows 2000, Windows XP, and Windows
Server 2003. Working together with DHCP servers, DNS servers that use DNS dynamic update can
now automate many aspects of name resolution that were once handled by manually configured
HOSTS files. DNS can also integrate with Active Directory to connect name resolution with directory
management.
When clients use DHCP, they can also get DNS configuration from the DHCP server. Figure 10 shows
the Internet Protocol [TCP/IP] Properties dialog box (reached through Network Connections), which
you can use to specify this setting by clicking the "Obtain DNS server address automatically" radio
button. In this case, DHCP helps you automate DNS settings on clients without using scripting.
Figure 10 Automating DNS Settings on Clients by Using the Windows Interface
See full-sized image
Tthe Ipconfig.exe command-line tool can also retrieve DNS client settings and perform tasks like
purging the DNS client resolver cache.
There may be situations, however, in which you need to configure DNS clients remotely or in
batches — for example, when replacing old DNS servers with new, making changes on servers, or
changing subnet arrangements. In such cases, manually configuring each host is not an efficient use
of administrative time. Here, as with other TCP/IP protocols, WMI provides methods and properties
of the Win32_NetworkAdapterConfiguration class that you can use to automate DNS client
configuration.
Note that Win32_ NetworkAdapterConfiguration does not provide a property or method that
explicitly corresponds to the "Obtain DNS server address automatically" setting. The
DNSServerSearchOrder property displays the IP addresses of any DNS servers configured on the
client whether they are set locally or obtained from the DHCP server.
Optionally, you can retrieve or set a value corresponding to "Obtain DNS server address
automatically" by using the two registry entries, DhcpNameServer and NameServer, which you can
find at the following registry location:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}
If the value of NameServer is null, the client tries to obtain a DNS server address automatically from
the DHCP server. If NameServer contains an IP address as its value, the IP address overrides any
DNS server address obtained from the DHCP server. In this case, any value in the DhcpNameServer
registry entry does not appear in the dialog box.
WMI also includes a DNS Server provider (first included in the Windows 2000 Resource Kit; now part
of the Windows Server 2003 operating system), which enables you to automate server operations
with scripting. Information about scripting the DNS Server provider is beyond the scope of this
paper.
The command-line tool Dnscmd.exe also offers extensive options for DNS server configuration.
This section provides scripting steps and sample scripts for these tasks:
• Displaying DNS client information.
• Enabling DNS.
• Changing the DNS server search order, the DNS domain, the DNS domain suffix search order, and
the DNS registration settings.
On This Page
Displaying DNS Client Information
Enabling DNS
Changing the DNS Server Search Order
Changing the DNS Domain
Changing the DNS Domain Suffix Search Order
Changing Dynamic DNS Registration Settings
Scenario: Changing DNS Servers and Domains
Tools for Scripting DNS on Clients
Displaying DNS Client InformationAs with DHCP, when you manage DNS on clients, the first step is usually to determine current
settings. Figure 11 shows the DNS tab of the Advanced TCP/IP Settings dialog box, which provides a
way to access these settings by using the Windows interface.
Figure 11 Displaying Current DNS Settings by Using the Windows Interface
See full-sized image
For scripts that use WMI, the Win32_NetworkAdapterConfiguration class offers several properties
that enable you to script DNS client configuration. Table 13 describes these DNS properties.
Table 13 Win32_NetworkAdapterConfiguration DNS Properties
Property Type DescriptionDNSDomain String Organization name followed by a period and an extension
that indicates the type of organization, such as
microsoft.com. The name can be any combination of the
letters A–Z, the numerals 0–9, and the hyphen (-), plus
the period (.) character used as a separator.
Example: "microsoft.com"
DNSDomainSuffixSearchOrder String Space-delimited list of DNS domain suffixes to be
appended to the end of host names during name
resolution. When attempting to resolve a fully-qualified
domain name (FQDN) from a host only name, the system
will first append the local domain name. If this is not
successful, the system will use the domain suffix list to
create additional FQDNs in the order listed and query
DNS servers for each
Example: "samples.microsoft.com
example.microsoft.com"
DNSEnabledForWINSResolution Boolean If TRUE, the DNS is enabled for name resolution over
Windows Internet Name Service (WINS) resolution. If the
Property Type Descriptionname cannot be resolved by using DNS, the name
request is forwarded to WINS for resolution.
DNSHostName String Host name used to identify the local computer for
authentication by some utilities. Other TCP/IP-based
utilities can use this value to acquire the name of the
local computer. Host names are stored on DNS servers in
a table that maps names to IP addresses for use by DNS.
The name can be any combination of the letters A–Z, the
numerals 0–9, and the hyphen (-), plus the period (.)
character used as a separator. By default, this value is
the Microsoft networking computer name, but the
network administrator can assign another host name
without affecting the computer name.
Example: "corpdns"
DNSServerSearchOrder String
array
Array of server IP addresses to be used in querying for
DNS servers.
DomainDNSRegistrationEnabled Boolean If TRUE, the IP addresses for this connection are
registered in DNS under the domain name of this
connection in addition to being registered under the
computer's full DNS name. The domain name of this
connection is either set using the
SetDNSDomain()method or assigned by DHCP. The
registered name is the host name of the computer with
the domain name appended. This property is new for
Windows XP.
FullDNSRegistrationEnabled Boolean If TRUE, the IP addresses for this connection are
registered in DNS under the computer's full DNS name.
The full DNS name of the computer is displayed on the
Network Identification tab in the System application in
Control Panel. This property is new for Windows XP.
All the properties in the previous table are read-only.
Table 14 describes the Win32_NetworkAdapterConfiguration methods to use for scripting DNS client
configuration.
Table 14 Win32_NetworkAdapterConfiguration DNS Methods
Method Parameters DescriptionEnableDNS DNSHostName – string
DNSDomain – string
DNSServerSearchOrder – array of
strings
DNSDomainSuffixSearchOrder -
string
Enables DNS on the client.
SetDNSDomain DNSDomain – string Allows for the setting of the DNS
domain. This is an instance-
dependent method call that applies
on a per-adapter basis. In
Method Parameters DescriptionWindows 2000, the setting applies to
the targeted adapter. In Windows NT
4.0, this setting is global.
SetDNSServerSearchOrder DNSServerSearchOrder – array of
strings
Uses an array of string elements to
set the server search order. To
remove all DNS servers from the
search order, use Null rather than an
empty string. This is an instance-
dependent method call that applies
on a per-adapter basis. After static
DNS servers are specified to start
using DHCP instead of static DNS
servers, you can call the method
without supplying "in" parameters.
In Windows 2000, the setting applies
to the targeted adapter. In
Windows NT 4.0, the setting is
global.
SetDNSSuffixSearchOrder DNSDomainSuffixSearchOrder –
string
Static method. Uses an array of
string elements to set the suffix
search order. For Windows NT only,
this is an instance-independent call
that applies to all adapters.
SetDynamicDNSRegistration FullDNSRegistrationEnabled –
Boolean
DomainDNSRegistrationEnabled –
Boolean
Indicates the mode of dynamic DNS
registration of IP addresses for this
IP-bound adapter.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that some problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
The following script, Dnssettings.vbs, displays the DNS-related settings that are exposed by
Win32_NetworkAdapterConfiguration. The DNSEnabledForWINSResolution property, which is
meaningful only if NetBIOS name resolution is used, is included instead in the settings script in the
WINS section of this paper. On Windows Server 2003, you can also read the host name from the
DNSHostName property of the Win32_ComputerSystem class; on older operating systems, this
Name property may return the NetBIOS name if it is different from the DNS name, depending on
client and network configuration.
Scripting Steps
Listing 28 displays the DNS client settings for each network adapter configuration on a computer.
1. Create a variable and assign the name of a computer to it. For the local computer, simply
specify "." as the computer name. To run this script remotely, specify the name of an
accessible remote computer on your network on which you have administrative privileges. The
name can be in the form of either a host name or an IP address.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. 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.
4. For each network adapter configuration in the collection, perform the following tasks.
5. Assign the Win32_NetworkAdapterConfiguration properties DNSHostName, Index, Description,
DNSDomain, DomainDNSRegistrationEnabled and FullDNSRegistrationEnabled to variables.
6. Iterate through the arrays returned by the DNSDomainSuffixSearchOrder and
DNSServerSearchOrder properties and convert them into formatted strings.
7. Concatenate the variables and labels into a string. On each iteration through another network
adapter, concatenate the strings for that adapter on to the original string.
8. Display the host name and the settings for each adapter.
Listing 28 Dnssettings.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
strDNSSuffixSO = ""
strDNSServerSO = ""
strDNSHostName = objNicConfig.DNSHostName
strIndex = objNicConfig.Index
strDescription = objNicConfig.Description
strDNSDomain = objNicConfig.DNSDomain
strDNSSuffixSO = ""
If Not IsNull(objNicConfig.DNSDomainSuffixSearchOrder) Then
For Each strDNSSuffix In objNicConfig.DNSDomainSuffixSearchOrder
strDNSSuffixSO = strDNSSuffixSO & VbCrLf & String(37, " ") & _
strDNSSuffix
Next
End If
strDNSServerSO = ""
If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
For Each strDNSServer In objNicConfig.DNSServerSearchOrder
strDNSServerSO = strDNSServerSO & VbCrLf & String(37, " ") & _
strDNSServer
Next
End If
strDomainDNSRegistrationEnabled = _
objNicConfig.DomainDNSRegistrationEnabled
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dnssettings.vbs
DNS Settings
Host Name: client1
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Domain:
DNS Domain Suffix Search Order:
DNS Server Search Order:
192.168.0.1
Domain DNS Registration Enabled:
Full DNS Registration Enabled:
Top of page
Enabling DNSFor situations where DNS must be enabled on hosts, for example, when a network is upgraded from
another name resolution system such as WINS, Win32_NetworkAdapterConfiguration offers the
EnableDNS() method.
The method takes four optional parameters: DNSHostName, DNSDomain, DNSServerSearchOrder,
and DNSDomainSuffixSearchOrder. The data types of the first two and the last are strings, of
DNSServerSearchOrder, an array of strings.
The Win32_ComputerSystem class includes a Rename() method that also lets you change the
computer name. To use the Rename() method, you must be a member of the local administrator
group. Note that you cannot use this method to rename remote hosts that are part of a domain. This
class also exposes JoinDomainOrWorkgroup() and UnjoinDomainOrWorkgroup() methods. All three
methods are new for Windows XP and Windows Server 2003.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 29 enables DNS for all network adapters on a computer, configuring the host name to
client1, the DNS domain to fabrikam.com, the DNS server search order as 192.168.0.1, 192.168.0.2,
and the DNS search order suffixes as fabrikam.com and na.fabrikam.com.
To carry out this task, the script performs the following steps:
1. Create variables to specify the computer name and parameters to pass to the EnableDNS
method.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtered for
instances where IP is enabled.
This returns a collection consisting of all the network adapter configurations on the computer.
4. For each network adapter configuration in the collection, perform the following tasks.
5. Display the index number and description of the network adapter.
6. Call the EnableDNS method, passing it the variables already initialized with the host name,
domain, DNS server search order and DNS domain suffix search order.
7. Check the value returned by the method, and display a success or error message accordingly.
8. Requery Win32_NetworkAdapterConfiguration and display the configuration after the
operation.
Listing 29 Dns-enable.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
On Error Resume Next
strComputer = "."
strDNSHostName = "client1"
strDNSDomain = "fabrikam.com"
arrDNSServerSearchOrder = Array("192.168.0.1", "192.168.0.2")
arrDNSDomainSuffixSearchOrder = Array("hr.fabrikam.com", "contoso.com")
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objNicConf = objWMIService.Get("Win32_NetworkAdapterConfiguration")
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName & VbCrLf & _
" Attempting to enable DNS"
intEnableDNS = objNicConf.EnableDNS(strDNSHostName, strDNSDomain, _
arrDNSServerSearchOrder, arrDNSDomainSuffixSearchOrder)
If intEnableDNS = 0 Then
WScript.Echo " Successfully enabled DNS."
ElseIf intEnableDNS = 1 Then
WScript.Echo " Successfully enabled DNS." & VbCrLf & " Must reboot."
Else
WScript.Echo " Unable to enable DNS."
End If
WScript.Echo VbCrLf & String(80,"-")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
strDNSHostName = objNicConfig.DNSHostName
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-enable.vbs
DNS Host Name: client1
Attempting to enable DNS
Unable to enable DNS.
--------------------------------------------------------------------------------
DNS Host Name: client1
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Domain:
DNS Server Search Order:
192.168.0.1
DNS Domain Suffix Search Order:
hr.fabrikam.com
contoso.com
Top of page
Changing the DNS Server Search OrderIf you do not use DHCP to determine the DNS servers for a client, you can configure each client with
a list of one or more DNS servers, in order of priority, to use for DNS name resolution.
Win32_NetworkAdapterConfiguration provides a DNSServerSearchOrder property that contains this
list in an array of strings, as well as a SetDNSServerSearchOrder method that modifies the property.
For the property and method, the first server on the list is the primary DNS server for the network
adapter. Using this method, you can replace the list of DNS servers with a new one, or you can
remove or replace one or more members in any position. The scripting techniques to accomplish
these changes vary depending on which variation is being performed. To remove all DNS servers
from the search order, you must use Null rather than an empty string.
This section provides scripting steps and sample scripts for these tasks:
• Replacing the entire DNS server search order list.
• Replacing one DNS server with another DNS server
• Adding a DNS server to the end or the beginning of the search order.
Replacing the DNS Server Search Order ListIf the search order of DNS servers must be changed, the simplest alternative is to replace the entire
list with a new search order list.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
For each network adapter, Listing 30 replaces the current DNS server search order list with a new
one.
1. Create a variable to specify the computer name.
2. Assign IP addresses to an array representing the new DNS server search order. Note that to
remove all DNS servers from the search order, you must use Null rather than an empty string.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. 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.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Display the index and current DNS server search order list of the network adapter
7. Call the SetDNSServerSearchOrder method of the Win32_NetworkAdapterConfiguration class,
passing it as a parameter the array of IP addresses representing the new DNS server search
order.
8. Check the value returned by the method, and display a success or error message.
9. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.
Listing 30 Dns-replaceserverlist.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
On Error Resume Next
strComputer = "."
arrNewDNSServerSearchOrder = Array("192.168.0.1", "192.168.0.2")
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "Computer: " & strComputer
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
WScript.Echo " DNS Server Search Order - Before:"
If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
For Each strDNSServer In objNicConfig.DNSServerSearchOrder
WScript.Echo " " & strDNSServer
Next
End If
intSetDNSServers = _
objNicConfig.SetDNSServerSearchOrder(arrNewDNSServerSearchOrder)
If intSetDNSServers = 0 Then
WScript.Echo " Replaced DNS server search order list."
Else
WScript.Echo " Unable to replace DNS server search order list."
End If
Next
WScript.Echo VbCrLf & String(80, "-")
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-replaceserverlist.vbs
Computer: .
Network Adapter 1
DNS Server Search Order - Before:
192.168.0.1
Replaced DNS server search order list.
--------------------------------------------------------------------------------
Network Adapter 1
DNS Server Search Order - After:
192.168.0.1
192.168.0.2
Replacing One DNS Server with AnotherIf only one DNS server has changed and the others are still valid, you may want to simply replace
the IP address of the old server with the IP address of the new server, keeping the address in the
same spot in the search order. Such a need might arise when a DNS server that is running on old
hardware is replaced by a new computer. After the change is made, the clients of the replaced
server must be reconfigured with the IP address of the new server.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 31 checks whether the IP address of a given server is on the DNS server search order list
(contained in a string array in the DNSServerSearchOrder property) for each network adapter
configuration on a computer. If the IP address is found, the script removes it and adds the IP
address of the new server in its place with the SetDNSServerSearchOrder method.
1. Create a variable to specify the computer name.
2. Assign IP addresses to the variables representing the old DNS server to be replaced and the
new server.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. 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.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Display the index and current DNS server search order list of the network adapter
7. Iterate through the list of DNS server IP addresses with a For loop, and if the IP address to be
replaced is found, replace it with the new IP address and set a Boolean flag.
8. If the flag is set to True, call the SetDNSServerSearchOrder method of the
Win32_NetworkAdapterConfiguration class, passing it as a parameter the updated array of IP
addresses representing the new DNS server search order.
9. Check the value returned by the method, and display a success or error message.
10. If the IP address to be replaced is not found, display a message.
11. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.
Listing 31 Dns-replaceserver.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
On Error Resume Next
strComputer = "."
strOldDNSServer = "192.168.0.2"
strNewDNSServer = "192.168.0.5"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "Computer: " & strComputer
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
arrDNSServerSearchOrder = objNicConfig.DNSServerSearchOrder
WScript.Echo " DNS Server Search Order - Before:"
If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
For Each strDNSServer In objNicConfig.DNSServerSearchOrder
WScript.Echo " " & strDNSServer
Next
End If
blnFound = 0
For i = 0 to UBound(arrDNSServerSearchOrder)
If arrDNSServerSearchOrder(i) = strOldDNSServer Then
arrDNSServerSearchOrder(i) = strNewDNSServer
blnFound = 1
End If
Next
If blnFound Then
retSetDNS = objNicConfig.SetDNSServerSearchOrder(arrDNSServerSearchOrder)
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-replaceserver.vbs
Computer: .
Network Adapter 1
DNS Server Search Order - Before:
192.168.0.3
192.168.0.1
192.168.0.2
192.168.0.4
Replaced 192.168.0.2 with 192.168.0.5 in DNS search order.
--------------------------------------------------------------------------------
Network Adapter 1
DNS Server Search Order - After:
192.168.0.3
192.168.0.1
192.168.0.5
192.168.0.4
Adding a DNS Server at the End of the Search OrderRather than replacing the IP address of an old DNS server with that of a new one in the DNS server
search order list, you might want to add the new server to the end of the list. This script shows how
to do this.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 32 adds a new DNS server at the end of the DNS server search order list for each network
adapter configuration on a computer.
1. Create a variable to specify the computer name.
2. Assign a new IP addresses to the variable representing the new DNS server.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. 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.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Create a variable, intNewArraySize, and set it to zero at the top of the loop to clear values
from previous iterations.
7. Display the index and current DNS server search order list of the network adapter
8. Assign the array returned by the DNSServerSearchOrder property to the variable
arrDNSServerSearchOrder.
9. Redimension (with the VBScript ReDim statement) arrDNSServerSearchOrder on line 20,
incrementing the number of array elements by one to accommodate the new DNS server IP
address. Note that in VBScript the number used by the ReDim statement is one less than the
resulting array size.
10. Assign the new DNS server's IP address to the final array element.
11. Call the SetDNSServerSearchOrder method of Win32_NetworkAdapterConfiguration, passing it
the changed array of IP addresses.
12. Check the value returned by the method, and display a success or error message.
13. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.
Listing 32 Dns-addserver-end.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
On Error Resume Next
strComputer = "."
strNewDNSServer = "192.168.0.4"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "Computer: " & strComputer
For Each objNicConfig In colNicConfigs
intNewArraySize = 0
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
arrDNSServerSearchOrder = objNicConfig.DNSServerSearchOrder
WScript.Echo " DNS Server Search Order - Before:"
If Not IsNull(arrDNSServerSearchOrder) Then
For Each strDNSServer In arrDNSServerSearchOrder
WScript.Echo " " & strDNSServer
Next
End If
WScript.Echo " Adding " & strNewDNSServer & " to end of " & _
"DNS search order."
intNewArraySize = UBound(arrDNSServerSearchOrder) + 1
ReDim Preserve arrDNSServerSearchOrder(intNewArraySize)
arrDNSServerSearchOrder(intNewArraySize) = strNewDNSServer
intSetDNS = _
objNicConfig.SetDNSServerSearchOrder(arrDNSServerSearchOrder)
If intSetDNS = 0 Then
WScript.Echo " Added " & strNewDNSServer & _
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-addserver-end.vbs
Computer: .
Network Adapter 1
DNS Server Search Order - Before:
192.168.0.1
192.168.0.2
Adding 192.168.0.4 to end of DNS search order.
Added 192.168.0.4 to end of DNS search order.
--------------------------------------------------------------------------------
Network Adapter 1
DNS Server Search Order - After:
192.168.0.1
192.168.0.2
192.168.0.4
Adding a DNS Server to the Beginning of the Search OrderFinally, you might want to add a new DNS server to the beginning of the search order list and this
script shows how. The main change here is to replace the one line of code that adds a new IP
address at the end of the array in Dns-addserver-end.vbs (line 21) with four lines below that move
each array element down in the array and add the new IP address at the top (lines 21–24).
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 33 adds a new DNS server at the beginning of the DNS server search order list for each
network adapter configuration on a computer.
1. Create a variable to specify the computer name.
2. Assign a new IP addresses to the variable representing the new DNS server.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. 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.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Create a variable, intNewArraySize, and set it to zero at the top of the loop to clear values
from previous iterations.
7. Display the index and current DNS server search order list of the network adapter.
8. Assign the array returned by the DNSServerSearchOrder property to the variable
arrDNSServerSearchOrder.
9. Redimension (with the VBScript ReDim statement) arrDNSServerSearchOrder on line 20,
incrementing the number of array elements by one to accommodate the new DNS server IP
address. Note that in VBScript the number used by the ReDim statement is one less than the
resulting array size.
10. Loop through all the array elements except the last (the new one which is still empty) and
assign each element to the following element in the array. This moves the whole array down
one step.
11. Assign the IP address of the new DNS server to the first array element (which has an index of
0).
12. Call the SetDNSServerSearchOrder method of Win32_NetworkAdapterConfiguration, passing it
the changed array of IP addresses.
13. Check the value returned by the method, and display a success or error message.
14. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.
Listing 33 Dns-addserver-top.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
On Error Resume Next
strComputer = "."
strNewDNSServer = "192.168.0.3"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "Computer: " & strComputer
For Each objNicConfig In colNicConfigs
intNewArraySize = 0
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
arrDNSServerSearchOrder = objNicConfig.DNSServerSearchOrder
WScript.Echo " DNS Server Search Order - Before:"
If Not IsNull(arrDNSServerSearchOrder) Then
For Each strDNSServer In arrDNSServerSearchOrder
WScript.Echo " " & strDNSServer
Next
End If
WScript.Echo " Adding " & strNewDNSServer & " to top of " & _
"DNS search order."
intNewArraySize = UBound(arrDNSServerSearchOrder) + 1
ReDim Preserve arrDNSServerSearchOrder(intNewArraySize)
For i = (intNewArraySize - 1) To 0 Step -1
arrDNSServerSearchOrder(i + 1) = arrDNSServerSearchOrder(i)
Next
arrDNSServerSearchOrder(0) = strNewDNSServer
intSetDNS = objNicConfig.SetDNSServerSearchOrder(arrDNSServerSearchOrder)
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-addserver-top.vbs
Computer: .
Network Adapter 1
DNS Server Search Order - Before:
192.168.0.1
192.168.0.2
192.168.0.4
Adding 192.168.0.3 to top of DNS search order.
Added 192.168.0.3 to top of DNS search order.
--------------------------------------------------------------------------------
Network Adapter 1
DNS Server Search Order - After:
192.168.0.3
192.168.0.1
192.168.0.2
192.168.0.4
Top of page
Changing the DNS DomainSometimes you might need to change the DNS domain on multiple clients — for example, when you
add a child domain or you merge two domains. If many or widely dispersed clients are involved,
scripting can be a time-saving and error-reducing alternative to manual configuration.
In Windows 2000, Windows XP, and Windows Server 2003, you can use the SetDNSDomain()
method of the Win32_NetworkAdapterConfiguration class to set the DNS domain for a specific
network adapter. You must pass this method a single parameter, a string indicating the name of the
new DNS domain. In Windows NT Server 4.0, the Win32_NetworkAdapterConfiguration setting
applies globally to all network adapters.
In Windows XP and Windows Server 2003, the Win32_ComputerSystem methods
JoinDomainOrWorkgroup() and UnjoinDomainOrWorkgroup() enable you to join or unjoin a computer
to or from an Active Directory domain. With these methods, the changes apply to all network
adapters. To make the same changes by using the Windows XP GUI, you can use the Network
Identification Wizard.
Win32_ComputerSystem also includes Domain and DomainRole properties that return Active
Directory domain membership and the role the computer plays in it — for example, member
workstation or domain controller. You may have to coordinate changes in DNS domains with
corresponding changes in Active Directory.
Changing the DNS Domain with Win32_NetworkAdapterConfigurationThe following script demonstrates how to use the SetDNSDomain() method of the
Win32_NetworkAdapterConfiguration class to set the DNS domain for all network adapters. Because
this method works on a per-adapter basis, you could also use it to set the DNS domain on a specific
network adapter.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
1. Create a variable to specify the computer name.
2. Create a variable to specify the new DNS domain name.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class.
This returns a collection consisting of all the network adapter configurations on the computer.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Display the index, description DNS host name and current DNS domain of the network adapter
7. Call the SetDNSDomain method of Win32_NetworkAdapterConfiguration, passing it the variable
containing the new DNS domain name.
8. Check the value returned by the method, and display a success or error message.
9. Requery Win32_NetworkAdapterConfiguration and display the new DNS domain.
Listing 34 Dns-setdomain.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
On Error Resume Next
strComputer = "."
strDNSDomain = "fabrikam.com"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & _
" Network Adapter " & objNicConfig.Index & VbCrLf & _
" " & objNicConfig.Description & VbCrLf & _
" DNS Domain - Before: " & objNicConfig.DNSDomain
intSetDomain = objNicConfig.SetDNSDomain(strDNSDomain)
If intSetDomain = 0 Then
WScript.Echo " Successfully set DNS domain to " & strDNSDomain
ElseIf intSetDomain = 1 Then
WScript.Echo " Successfully set DNS domain to " & strDNSDomain & _
VbCrLf & " Must reboot."
Else
WScript.Echo " Unable to set DNS domain."
End If
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-setdomain.vbs
DNS Host Name: client1
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Domain - Before:
Successfully set DNS domain to fabrikam.com
--------------------------------------------------------------------------------
DNS Host Name: client1
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Domain - After: fabrikam.com
Changing the Domain with Win32_ComputerSystemThe following script demonstrates how to use the JoinDomainOrWorkgroup() method of the
Win32_ComputerSystem class to join a computer to an Active Directory domain. The changes apply
to all network adapters, in contrast to the SetDNSDomain() method of the
Win32_NetworkAdapterConfiguration class, which applies changes only to each specified adapter.
Win32_ComputerSystem also provides an UnjoinDomainOrWorkgroup() method. Both the
JoinDomainOrWorkgroup() and UnjoinDomainOrWorkgroup() methods are available only on
Windows XP and Windows Server 2003.
You may have to coordinate domain changes with corresponding changes in Active Directory.
Table 15 describes the five parameters that the JoinDomainOrWorkgroup() method accepts.
Table 15 JoinDomainOrWorkgroup() Parameters
Parameter DescriptionName The name of the domain or workgroup to join. Cannot be NULL.
Password Must be specified if an alternative Username parameter is passed. Can be NULL if
no Username is passed.
Username NetBIOS name and user account, in the form DOMAIN\user. If this parameter is
NULL, the credentials under which the script is run are used.
AccountOU Optional. Can be NULL. The fully distinguished name of the Active Directory
organizational unit, for example: OU=HR, DC=fabrikam, DC=com.
FJoinOptions A set of bit flags that specify options for joining a domain or workgroup. If you do
not set this parameter, the default of 1 (Join Domain) is used and the name
specified in the first parameter is assumed to be a workgroup. You can set 0 or
more of these parameters simultaneously by OR-ing the requisite values together,
as the following script illustrates.
Table 16 describes valid values for the FjoinOptions parameter of JoinDomainOrWorkgroup()
method.
Table 16 FJoinOptions Values
Value:Decimal& Hex
Value Meaning
1
&h00001
Join Domain Default. Joins a computer to a domain. If this value is not
specified, the join is a computer to a workgroup.
2
&h00002
Acct Create Creates an account on a domain.
4
&h00004
Acct Delete Deletes an account when a domain exists.
16
&h00010
Win9X Upgrade The join operation is part of an upgrade from Windows 95
or Windows 98 to Windows NT 4.0 or Windows 2000.
32
&h00020
Domain Join If Joined Allows a join to a new domain even if the computer is
already joined to a domain.
64
&h00040
Join Unsecure Performs an unsecured join.
128
&h00080
Machine Password
Passed
The computer, not the user, password is passed. This
option is only valid for unsecure joins.
256
&h00100
Deferred SPN Set Writing SPN and DnsHostName attributes on the
computer object should be deferred until the rename that
follows the join.
262144
&h40000
Install Invocation The APIs were invoked during install.
In addition, Win32_ComputerSystem contains an UnjoinDomainOrWorkgroup() method (also new for
Windows XP), which removes a computer from a domain.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 35 changes the domain globally for the computer system.
1. Define a constant, JOIN_DOMAIN, and set it equal to 1.
Note
Note that this value joins a computer to a domain only if it does not already belong to one. To
join a computer that already is joined to a domain to a new domain, create a constant,
DOMAIN_JOIN_IF_JOINED, and set it equal to 32. Then in the call to the
JoinDomainOrWorkgroup method, pass DOMAIN_JOIN_IF_JOINED as the final parameter rather
than JOIN_DOMAIN.
2. Create a variable to specify the computer name.
3. Create a variable to specify the new DNS domain name.
4. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
5. Use the ExecQuery method to query the Win32_ComputerSystem class.
6. This returns a collection consisting of all computer systems on the computer. Only one
computer system is returned.
7. For each network adapter configuration in the collection, perform the following tasks.
8. Display the computer name and current domain.
9. Call the JoinDomainOrWorkgroup method of Win32_ComputerSystem, passing it two
parameters: the variable representing the new domain name and the constant representing
the value 1, which indicates the Join Domain option. Mark the places of blank optional
parameters with commas.
10. Check the value returned by the method, and display a success or error message.
11. Requery Win32_ComputerSystem and display the changed domain.
12. Use a Select Case statement to convert the integer value returned by the DomainRole
property into a descriptive string and display it.
Listing 35 Dns-setdomain-global.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
On Error Resume Next
Const JOIN_DOMAIN = 1
strComputer = "."
strDomainName = "fabrikam.com"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colCompSystems = objWMIService.ExecQuery _
("SELECT * FROM Win32_ComputerSystem")
For Each objCompSystem In colCompSystems
WScript.Echo VbCrLf & "Computer Name: " & LCase(objCompSystem.Name)
WScript.Echo " Domain - Before: " & LCase(objCompSystem.Domain)
intJoinDomain = objCompSystem.JoinDomainOrWorkgroup(strDomainName,,,, _
JOIN_DOMAIN)
If intJoinDomain = 0 Then
WScript.Echo " Joined computer to " & strDomainName & " domain."
ElseIf intJoinDomain = 1 Then
WScript.Echo " Joined computer to " & strDomainName & " domain." & _
VbCrLf & " Must reboot."
Else
WScript.Echo " Unable to join computer to " & strDomainName & _
" domain."
WScript.Echo "Return value of JoinDomainOrWorkgroup method: " & intJoinDomain
End If
Next
WScript.Echo VbCrLf & String(80, "-")
Set colCompSystems = objWMIService.ExecQuery _
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-setdomain-global.vbs
Computer Name: client1
Domain - Before:
Joined computer to fabrikam.com domain.
--------------------------------------------------------------------------------
Computer Name: client1
Domain - After: fabrikam.com
Domain Role: Member Workstation
Top of page
Changing the DNS Domain Suffix Search OrderBesides changing a computer’s DNS domain, you can also set the search order for the DNS domain
suffix. This may be necessary when the host must try to resolve unqualified names on DNS servers
in more than one domain. Such a situation might occur when a network includes multiple secondary
DNS servers in different domains, or when a multihomed computer has each network adapter joined
to a different domain.
The following script sets the DNS domain suffixes that correspond to the names you would enter in
the text box under Append these DNS suffixes (in order) on the DNS tab of the Advanced TCP/IP
Settings dialog box.
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
SetDNSSuffixSearchOrder is a static method, which means that it applies to all instances of the
Win32_NetworkAdapterConfiguration class (that is, to all IP-enabled network adapters). This means
that you can use the simpler Get() method of the SWbemServices object (returned by the previous
GetObject call to the winmgmts: moniker) to get an object representing the whole class, rather than
using the more complex ExecQuery() method with a WQL query to get a collection of objects
representing instances of the class. The Get() method appears on line 19:
Set objNetworkSettings = objWMIService.Get("Win32_NetworkAdapterConfiguration")
Instead of simply calling the SetDNSSuffixSearchOrder method without parameters, as you do with
EnableDHCP, you must pass it an array of strings containing the suffix names.
If you needed only to call the SetDNSSuffixSearchOrder method in a script, you could use more
compact ways of binding to the Win32_NetworkAdapterConfiguration class. Here are two examples:
Set objNicConfig = GetObject("winmgmts:\\" & strComputer &_
"\root\cimv2:Win32_NetworkAdapterConfiguration")
Set objNicConfig = GetObject("winmgmts:").Get _
("Win32_NetworkAdapterConfiguration")
Which way is best in a specific context is often determined by coding style or organizational
standards.
Scripting Steps
Listing 36 replaces the old DNS domain suffix search order list with a new list for all network
adapters.
1. Create a variable to specify the computer name.
2. Create an array variable to specify the list of DNS domain suffixes.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. 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.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Check that the DNSDomainSuffixSearchOrder property is not Null
7. Iterate through the array of strings returned by the DNSDomainSuffixSearchOrder property,
8. Concatenate the array elements into a single string.
9. Display the string containing the list of DNS domain suffixes in order.
10. Call the SetDNSSuffixSearchOrder method of Win32_NetworkAdapterConfiguration, passing it
one parameter: the array containing the list of DNS domain suffixes.
11. Check the value returned by the method, and display a success or error message.
12. Requery Win32_NetworkAdapterConfiguration and display the changed list of DNS domain
suffixes.
Listing 36 Dns-replacesuffixlist.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
On Error Resume Next
strComputer = "."
arrNewDNSSuffixSearchOrder = Array("hr.fabrikam.com", "contoso.com")
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & _
" Network Adapter " & objNicConfig.Index & VbCrLf & _
" " & objNicConfig.Description & VbCrLf & _
" DNS Domain Suffix Search Order - Before:"
If Not IsNull(objNicConfig.DNSDomainSuffixSearchOrder) Then
For Each strDNSSuffix In objNicConfig.DNSDomainSuffixSearchOrder
WScript.Echo " " & strDNSSuffix
Next
End If
Next
WScript.Echo VbCrLf & String(80, "-")
Set objNetworkSettings = _
objWMIService.Get("Win32_NetworkAdapterConfiguration")
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-replacesuffixlist.vbs
DNS Host Name: client1
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Domain Suffix Search Order - Before:
--------------------------------------------------------------------------------
Replaced DNS domain suffix search order list.
--------------------------------------------------------------------------------
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Domain Suffix Search Order - After:
hr.fabrikam.com
contoso.com
Top of page
Changing Dynamic DNS Registration SettingsAs IP addresses change for DHCP clients, DNS registration and dynamic update automate the
process of keeping host name and IP address mappings change current on your DNS servers.
Although previously this update process had to be manually performed by administrators, DNS
dynamic update (RFC 2136) allows clients and DHCP servers to keep address (A) and pointer record
(PTR) resource records up-to-date on the DNS server without manual intervention.
As usual, the Win32_NetworkAdapterConfiguration class provides read-only properties to expose
these DNS registration and update settings and a method to change them. The parameters you
must pass to the SetDynamicDNSRegistration method, as well as the two Boolean properties they
set, map to two check boxes at the bottom of the DNS tab of the Advanced TCP/IP Settings dialog
box. “Register this connection’s addresses in DNS” in the Windows interface is equivalent to the
FullDNSRegistrationEnabled property; “Use this connection’s DNS suffix in DNS registration” is
equivalent to the DomainDNSRegistrationEnabled property. Both properties and the method are
new for Windows XP and Windows Server 2003. The value of DomainDNSRegistrationEnabled, the
default of which is False, is used only if FullDNSRegistrationEnabled is True; otherwise it is ignored.
You can look in the Windows interface to find the name to which the FullDNSRegistrationEnabled
property refers. Open Control Panel, click System, click the Computer Name tab, and then view the
Full computer name field. The value in this field consists of the host name with the domain name
appended. If FullDNSRegistrationEnabled is True, the IP addresses for the network adapter are
registered in DNS by using this name.
If the DomainDNSRegistrationEnabled property is True, the IP addresses are additionally registered
in DNS by using the DNSDomain property for the specific network adapter.
For example, on a multihomed computer whose network adapters are each connected to a different
network with a different domain structure, you might need to use connection-specific DNS suffixes
in domain registration. In such cases, the client might want to register a different domain suffix for
each network connection. Setting FullDNSRegistrationEnabled and DomainDNSRegistrationEnabled
both to True would enable this.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
This script changes settings for how dynamic DNS registration is accomplished by using the
SetDynamicDNSRegistration() method of the Win32_NetworkAdapterConfiguration class to modify
the DomainDNSRegistrationEnabled and FullDNSRegistrationEnabled properties.
The method and properties are new for Windows XP and Windows Server 2003. The script does not
check for the operating system version; however, if the SetDynamicDNSRegistration does not return
a 0, indicating success, the script traps the error and displays a message.
1. Create a variable to specify the computer name.
2. Create two Boolean variables to specify the desired settings for the
DomainDNSRegistrationEnabled and FullDNSRegistrationEnabled properties.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering
the WQL query with “WHERE IPEnabled = True.”
This returns a collection that consists of all the network adapter configurations on the
computer for which IP is enabled.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Display the current DNS dynamic registration settings.
7. Call the SetDynamicDNSRegistration method of Win32_NetworkAdapterConfiguration, passing
it the two Boolean parameters set at the beginning of the script.
8. Check the value returned by the method, and display a success or error message.
9. Requery Win32_NetworkAdapterConfiguration and display the changed DNS dynamic
registration settings.
Listing 37 Dns-setdynreg.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
On Error Resume Next
strComputer = "."
blnFullDNSRegistrationEnabled = True
blnDomainDNSRegistrationEnabled = True
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & _
" Network Adapter " & objNicConfig.Index & VbCrLf & _
" " & objNicConfig.Description & VbCrLf & _
" DNS Full Registration Enabled - Before: " & _
objNicConfig.FullDNSRegistrationEnabled & VbCrLf & _
" DNS Domain Registration Enabled - Before: " & _
objNicConfig.DomainDNSRegistrationEnabled
intDynReg = objNicConfig.SetDynamicDNSRegistration _
(blnFullDNSRegistrationEnabled, blnDomainDNSRegistrationEnabled)
If intDynReg = 0 Then
WScript.Echo VbCrLf & " Successfully set dynamic DNS registration."
ElseIf intDynReg = 1 Then
WScript.Echo VbCrLf & _
" Successfully set dynamic DNS registration." & _
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>dns-setdynreg.vbs
DNS Host Name: client1
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Full Registration Enabled - Before:
DNS Domain Registration Enabled - Before:
Successfully set dynamic DNS registration.
--------------------------------------------------------------------------------
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Full Registration Enabled - After: True
DNS Domain Registration Enabled - After: True
Top of page
Scenario: Changing DNS Servers and DomainsIn times of major business changes, such as mergers, acquisitions, and reorganizations, the DNS
domain hierarchy of an organization may change and hosts may have to be reconfigured to function
within the new structure.
In this scenario, the IT department at Fabrikam, Inc. is assigning clients that were formerly in the
top-level fabrikam.com domain to different subdomains: hr.fabrikam.com, it.fabrikam.com and
ac.fabrikam.com. Each new subdomain requires a new DNS server search order for the clients on it.
The primary DNS server for each subdomain will also be a backup for the other two subdomains.
This script uses the Win32_NetworkAdapterConfiguration methods SetDNSDomain() and
SetDNSServerSearchOrder(), rather than EnableDNS(). The latter requires two other optional
parameters, which could be left blank; the first two methods set precisely the parameters required
by this example. If necessary, you could easily expand the script to also configure the hosts’
dynamic registration settings with the SetDynamicDNSRegistration() method.
Keep in mind that in an operation like this one, configuring the client is only part of the task: you
must also make corresponding changes on the DNS servers. Scripting DNS servers is beyond the
scope of this paper.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 38 takes a text file as input. You must create this file before running the script. The path to
the file is specified in a variable; in this example, it is C:\Scripts\Hosts.txt. Each line of the text file
contains a host name and a new domain name, separated by a comma (with no spaces in between).
The final line must NOT be terminated with an Enter character, because the following line would be
read by the script as an empty entry.
client1,hr
client2,it
server1,ac
For each host, the script assigns the new domain name and a new DNS server search order. The
new order depends on the new domain name: each subdomain has its own primary DNS server,
which serves as a backup for the other two subdomains.
The script creates a comma-separated values (.csv) text file and logs the results of these operations
to it. The path to the file is specified in a variable; in this case, it is C:\Scripts\Newhosts.csv.
1. Define constants for FileSystemObject.
2. Create variables specifying the paths to the input and output files.
3. Create variables specifying the name of the top-level domain.
4. Create three arrays of strings containing the DNS server search orders for each sub-domain.
5. Create a FileSystemObject and use it to open the file and read the contents into a string.
6. Call the GetInput function, passing it the name of the input text file. The function reads the
contents of the input file and returns them as a string.
7. Use the VBScript Split function, with the VbCrLf constant as the delimiter, to break down the
string from the input file into an array with each element consisting of a line of the text file,
which should contain the name of a computer and a sub-domain.
8. Check to see if the specified output file exists. If so, open it for appending. If not, create it and
open it for writing.
9. Iterate through each array element returned by splitting the lines of the input file.
10. Again using Split, divide each element of the array at the comma, reading the host name into
one variable and the sub-domain name into another.
11. Concatenate the sub-domain name with the top-level domain name to obtain the full domain
name.
12. Display the host name.
13. Call the PingClient function, passing it the host name.
14. If the ping receives a reply, connect to the WMI service and trap for an error.
15. If no error occurs in connecting to WMI, query the WMI service for the collection of all IP-
enabled network adapters.
16. Call the GetSettings subroutine to display current DNS settings and write them to the output
file.
17. Call the ChangeDNS function, which makes the changes in domain and DNS search order
specified in the input file and logs the results to the output file.
18. Again call the GetSettings subroutine to display the changed DNS settings and write them to
the output file.
19. If an error occurred connecting to WMI, display error information.
20. If the ping does not receive a reply, display an error message.
21. The GetInput function takes a string with the name of the input text file as a parameter. The
function returns a string containing the text from the input file. If the file is empty or cannot
be found, the function displays an error message and terminates the script.
22. The PingClient function takes a string with the name of a host computer as a parameter. The
function returns True if the ping receives a reply and False if not.
23. The GetSettings subroutine displays for each network adapter the index number, description,
DNS domain, DNS server search order, IP addresses, and subnet masks.
24. The ChangeDNS subroutine selects a DNS server search order based on the sub-domain
specified for the host in the input file. If the sub-domain is one of the ones included in the
logic of the Select Case statement, the subroutine attempts to call the SetDNSDomain method
with the name of the new domain. If this method is successful, the subroutine then attempts
to call the SetDNSServerSearchOrder method with the selected DNS server search order. The
subroutine logs the results and any errors to the output file.
Listing 38 Dns-move.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
On Error Resume Next
' Constants for FileSystemObject
Const FOR_READING = 1
Const FOR_WRITING = 2
Const FOR_APPENDING = 8
' Paths to input and output files. Input file must be text file with name
' of accessible machine, comma, and valid domain name on each line.
strFileInput = "c:\scripts\hosts.txt"
strFileOutput = "c:\scripts\newhosts.csv"
' Domain name and DNS servers corresponding to subdomains
strTopDomain = "fabrikam.com"
arrDNSSrv1 = Array("192.168.0.1", "192.168.0.2", "192.168.0.3") 'hr
arrDNSSrv2 = Array("192.168.0.2", "192.168.0.3", "192.168.0.1") 'it
arrDNSSrv3 = Array("192.168.0.3", "192.168.0.1", "192.168.0.2") 'ac
' Create a Script Runtime FileSystemObject.
Set objFSO = CreateObject("Scripting.FileSystemObject")
' If the input file exists, dump contents of input file into a string.
strInput = GetInput(strFileInput)
' Get computer info by breaking input stream into array at line breaks.
arrHosts = Split(strInput, VbCrLf)
' Check to see if the output file exists. If so, open it for appending.
' If not, create it and open it for writing.
If objFSO.FileExists(strFileOutput) Then
When you use Cscript.exe to run this script, the output is displayed in a comma-delimited text file
named C:\Scripts\Newhosts.csv. You can open a .csv file as a spreadsheet. Output similar to the
following is displayed on the monitor when the script runs.
C:\scripts>dns-move.vbs
Host: client1
Host: client2
Host: server1
Inventory complete. Data written to c:\scripts\newhosts.csv.
Top of page
Tools for Scripting DNS on ClientsTable 17 outlines the available Windows tools to use for scripting DNS on clients.
Table 17 Tools for Scripting DNS on Clients
Technology Tool Where AvailableCommand-line
tools
Dnscmd.exe: DNS Server
Troubleshooting Tool
Windows Server 2003 Support Tools
Command-line
tools
Dnslint.exe Windows Server 2003 Support Tools
Command-line
tools
DNSRECORD.PL Windows 2000 Resource Kit
Command-line
tools
DNSSERVER.PL Windows 2000 Resource Kit
Command-line
tools
DNSZONES.PL Windows 2000 Resource Kit
Command-line
tools
NETDNSCONFIG.PL Windows 2000 Resource Kit
Command-line
tools
Netsh.exe Windows operating systems1
Command-line
tools
Nslookup.exe Windows operating systems
WSH None
WMI Win32_ComputerSystem
WMI Win32_OperatingSystem
WMI Win32_NetworkAdapterConfiguration
WMI Win32_NTDomain Windows XP and Windows Server 2003 only
1 Windows 2000, Windows XP, and Windows Server 2003. May also be present on other versions of Windows.
Table 18 outlines the available registry subkeys to use for scripting DNS on clients.
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 18 Registry Subkeys Related to Scripting DNS on Clients
Registry SubkeysHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dnscache
Automating TCP/IP Networking on ClientsPart 6: Scripting WINS on Clients
Published: July 12, 2004Although Windows Internet Name Service (WINS) is provided on Windows XP and Windows
Server 2003 mainly for backward compatibility with older NetBIOS-based versions of Windows and
network applications, WINS is still in wide use as the name resolution system for NetBIOS names.
Figure 12 shows the WINS tab of the Advanced TCP/IP Settings dialog box, which provides access to
these settings by means of the Windows interface.
Figure 12 Setting NetBIOS Name Resolution by Using the Windows Interface
See full-sized image
For scripts that use WMI, the Win32_NetworkAdapterConfiguration class provides functionality to
manage WINS configuration that is comparable to that offered for managing DNS.
If your network uses both WINS and DNS, WINS can use DNS as a backup for name resolution, and
vice versa. When you enable WINS by using Win32_NetworkAdapterConfiguration, one of the
parameters passed to the EnableWINS method can configure WINS to query the DNS server for
names that it cannot resolve during NetBIOS name resolution.
Win32_NetworkAdapterConfiguration also offers a method that can enable or disable the default
operation of NetBIOS over TCP/IP, and if DHCP is used, can configure a client to get NetBIOS settings
from DHCP. Table 19 describes the WINS properties for the Win32_NetworkAdapterConfiguration
class.
Table 19 WINS Properties for the Win32_NetworkAdapterConfiguration Class
Property Type DescriptionDNSEnabledForWINSResolution Boolean If TRUE, the DNS is enabled for name resolution over
WINS resolution. If the name cannot be resolved using
DNS, the name request is forwarded to WINS for
resolution.
TcpipNetbiosOptions
New for Windows XP
Uint32 Bitmap of the possible settings related to NetBIOSover
TCP/IP. Values are as follows:
0 = Enable NetBIOS via DHCP
1 = Enable NetBIOS
2 = Disable NetBIOS
WINSEnableLMHostsLookup Boolean If TRUE, local lookup files are used. Lookup files will
contain a map of IP addresses to host names. If they
exist on the local system, they will be found in
%systemroot%\System32\Drivers\etc.
WINSHostLookupFile String Path to a WINS lookup file on the local system. This file
will contain a map of IP addresses to host names. If the
file specified in this property is found, it will be copied to
the %systemroot%\System32\Drivers\etc folder of the
local system. Valid only if the
WINSEnableLMHostsLookup property is TRUE.
WINSPrimaryServer String IP address for the primary WINS server.
WINSScopeID String Value appended to the end of the NetBIOS name that
isolates a group of computer systems communicating
with only each other. It is used for all NetBIOS
transactions over TCP/IP communications from that
computer system. Computers configured with identical
scope identifiers are able to communicate with this
computer. TCP/IP clients with different scope identifiers
disregard packets from computers with this scope
identifier. Valid only when the EnableWINS method
executes successfully.
WINSSecondaryServer String IP address for the secondary WINS server.
All the properties in the previous table are read-only.
Table 20 describes the WINS methods for the Win32_NetworkAdapterConfiguration class.
Table 20 WINS Methods for the Win32_NetworkAdapterConfiguration Class
Method Parameters DescriptionEnableWINS DNSEnabledForWINSResolution - Boolean Static method. Enables WINS settings
specific to TCP/IP, but independent of the
Method Parameters DescriptionWINSEnableLMHostsLookup – Boolean
WINSHostLookupFile –string
WINSScopeID - string
network adapter.
SetWINSServer WINSPrimaryServer – string
WINSSecondaryServer – string
Static method. Sets the primary and
secondary WINS servers on this TCP/IP-
bound network adapter. This method is
applied independently of the network
adapter.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that some problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
This section provides scripting steps and sample scripts for these WINS-related tasks:
• Displaying WINS client information
• Enabling NETBIOS.
• Enabling WINS.
• Setting WINS servers for a client.
Displaying WINS Client InformationIn managing WINS on clients, as with DHCP and DNS, the first step is usually to determine current
settings. This section demonstrates how to retrieve current NetBIOS and WINS settings.
Scripting Steps
Listing 39 displays the WINS client settings for each network adapter configuration on a computer.
1. Create a variable and assign the name of a computer to it. For the local computer, simply
specify "." as the computer name. To run this script remotely, specify the name of an
accessible remote computer on your network on which you have administrative privileges. The
name can be in the form of either a host name or an IP address.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. 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.
4. For each network adapter configuration in the collection, perform the following tasks.
5. Assign the Win32_NetworkAdapterConfiguration properties DNSHostName to a variable.
6. Use a Select Case statement to convert the values of the TcpipNetbiosOptions property to
descriptive strings.
7. Concatenate labels, the descriptive string for the TcpipNetbiosOptions property, and the values
for Win32_NetworkAdapterConfiguration properties Index, Description, WINSPrimaryServer,
WINSSecondaryServer, WINSScopeID, WINSEnableLMHostsLookup, WINSHostLookupFile and
DNSEnabledForWINSResolution into a string.
8. On each succeeding iteration through another network adapter, concatenate the strings for
that adapter onto the original string.
9. Display the host name and the settings for each adapter.
Listing 39 Winssettings.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
strDNSHostName = objNicConfig.DNSHostName
intNetBIOS = objNicConfig.TcpipNetbiosOptions
Select Case intNetBIOS
Case 0 strNetBIOS = "Use NetBIOS setting from the DHCP server."
Case 1 strNetBIOS = "Enable NetBIOS over TCP/IP."
Case 2 strNetBIOS = "Disable NetBIOS over TCP/IP."
Case Else strNetBIOS = "Unable to determine setting for NetBIOS " & _
"Over TCP/IP."
End Select
strWINSSettings = strWINSSettings & VbCrLf & VbCrLf & _
" Network Adapter " & objNicConfig.Index & VbCrLf & _
" " & objNicConfig.Description & VbCrLf & VbCrLf & _
" NetBIOS: " & strNetBIOS & VbCrLf & _
" WINS Primary Server: " & _
objNicConfig.WINSPrimaryServer & VbCrLf & _
" WINS Secondary Server: " & _
objNicConfig.WINSSecondaryServer & VbCrLf & _
" WINS Scope ID: " & _
objNicConfig.WINSScopeID & VbCrLf & _
" WINS Enable LMHosts Lookup: " & _
objNicConfig.WINSEnableLMHostsLookup & VbCrLf & _
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>winssettings.vbs
WINS Settings
Host Name: client1
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
NetBIOS: Enable NetBIOS over TCP/IP.
WINS Primary Server:
WINS Secondary Server:
WINS Scope ID:
WINS Enable LMHosts Lookup: True
WINS Host Lookup File:
DNS Enabled For WINS Resolution: False
Top of page
Enabling NetBIOSBecause WINS resolves NetBIOS names, you must enable NetBIOS when you enable WINS on a
client. When DHCP is enabled, the client can obtain NetBIOS settings from the DHCP server.
Otherwise, when a client is using a static IP address, you must configure WINS settings on that
client.
The setting for NetBIOS over TCP/IP is exposed in the Windows interface by the three radio buttons
at the bottom of the WINS tab of the Advanced TCP/IP settings dialog box (see Figure 12).
Table 21 shows how these radio buttons correspond to the three possible values of the
TcpipNetbiosOptions property of Win32_Network AdapterConfiguration, which you can set by using
the SetTCPIPNetBIOS() method.
Table 21 Values of the TcpipNetbiosOptions Property
Value Meaning Use0 Enable NetBIOS by means
of DHCP
When DHCP is enabled in order to obtain NetBIOS settings from the
DHCP server. If a static IP address is used or the DHCP server does
not provide a NetBIOS setting, this setting enables NetBIOS over
TCP/IP.
1 Enable NetBIOS When static IP addressing is enabled and DHCP is disabled.
2 Disable NetBIOS When NetBIOS is not being used on the network.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 40 enables NetBIOS on a network adapter. It uses the SetTCPIPNetBIOS() method of the
Win32_NetworkAdapterConfiguration class to set the TcpipNetbiosOptions property. This property is
new for Windows XP.
1. Define constants to represent the three possible values of the TcpipNetbiosOptions property.
2. Create a variable to specify the computer name.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. 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.
5. Display the name of the computer.
6. For each network adapter configuration in the collection, perform the following tasks.
7. Display the Index property of the network adapter.
8. Call the SetTCPIPNetBIOS method of Win32_NetworkAdapterConfiguration, passing it as the
single parameter one of the three constants representing values of the TcpipNetbiosOptions
property.
9. Check the value returned by the method, and display a success or error message.
10. Requery Win32_NetworkAdapterConfiguration.
11. Display the new TcpipNetbiosOptions property, using a Select Case statement to convert the
integer value into an explanatory string.
Listing 40 Wins-enablenetbios.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
On Error Resume Next
Const ENABLE_NETBIOS_VIA_DHCP = 0
Const ENABLE_NETBIOS = 1
Const DISABLE_NETBIOS = 2
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "Host Name: " & strComputer
For Each objNicConfig in colNicConfigs
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & _
" " & objNicConfig.Description & VbCrLf & _
" Attempting to set NetBIOS over TCP/IP default."
intNetBIOS = objNicConfig.SetTCPIPNetBIOS(ENABLE_NETBIOS_VIA_DHCP)
If intNetBIOS = 0 Then
WScript.Echo " Successfully set NetBIOS over TCP/IP default."
ElseIf intNetBIOS = 1 Then
WScript.Echo " Successfully set NetBIOS over TCP/IP default." & _
VbCrLf & " Must reboot."
Else
WScript.Echo " Unable to set NetBIOS default."
End If
Next
WScript.Echo VbCrLf & String(80, "-")
Set colNicConfigs = objWMIService.ExecQuery _
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>wins-enablenetbios.vbs
Host Name: .
Network Adapter 1 3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX
Compatible) - Packet Scheduler Miniport
Attempting to set NetBIOS over TCP/IP default.
Successfully set NetBIOS over TCP/IP default.
--------------------------------------------------------------------------------
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
NetBIOS Over TCP/IP: Enable NetBIOS over TCP/IP
Top of page
Enabling WINSIf NetBIOS is enabled through DHCP, you need not enable WINS or assign WINS servers manually
because the client gets these settings from the DHCP server. However, if NetBIOS is enabled
independently of DHCP, you must enable WINS and assign IP addresses for a primary server and
optionally, for a secondary WINS server.
Win32_NetworkAdapterConfiguration offers two methods to accomplish this: one that enables WINS
and configures four WINS settings; another that assigns primary and secondary WINS servers.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 41 enables WINS and sets four parameters that are passed to the EnableWINS method.
Table 22 describes the parameters of the EnableWINS method.
Table 22 Parameters of the EnableWINS Method
Parameter Type DescriptionDNSEnabledForWINSResolution Boolean A value indicating whether to enable DNS as the backup
method for name resolution.
WINSEnableLMHostsLookup Boolean A value indicating whether to enable the use of the
LMHOSTS lookup file to map NetBIOS names to IP
addresses.
WINSHostLookupFile String The path to the LMHOSTS lookup file. This parameter is
optional and is used only if the previous value
(WINSEnableLMHostsLookup) is True.
WINSScopeID String the scope identifier to be appended to the end of the
computer's NetBIOS name. Computers that use the same
scope identifier can communicate with each other.
The name of each parameter is also the name of the property that can be used to retrieve the
value.
EnableWINS is a static method that applies to all instances of the class, which in this case means all
network adapters.
1. Create a variable to specify the computer name.
2. Create variables to specify the four parameters to be passed to the EnableWINS method.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. Call the Get method on the Win32_NetworkAdapterConfiguration class.
This returns an object reference to the Win32_NetworkAdapterConfiguration class itself, rather
than a collection of its instances. This reference to the class must be used to call the static
method EnableWINS.
5. Display the name of the computer.
6. Call the static method EnableWINS of Win32_NetworkAdapterConfiguration, passing it the four
parameters defined above.
7. Check the value returned by the method, and display a success or error message.
8. Use the ExecQuery method to requery the Win32_NetworkAdapterConfiguration class, filtering
the WQL query with “WHERE IPEnabled = True.”
9. Display the settings that have been configured with the EnableWINS method.
Listing 41 Wins-enable.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
On Error Resume Next
strComputer = "."
blnDNSEnabledForWINSResolution = True
blnWINSEnableLMHostsLookup = True
strWINSHostLookupFile = ""
strWINSScopeID = "WORKGROUP"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objNicConf = objWMIService.Get("Win32_NetworkAdapterConfiguration")
WScript.Echo VbCrLf & "Host Name: " & strComputer & VbCrLf & _
" Attempting to enable WINS"
intEnableWINS = objNicConf.EnableWINS(blnDNSEnabledForWINSResolution, _
blnWINSEnableLMHostsLookup, strWINSHostLookupFile, strWINSScopeID)
If intEnableWINS = 0 Then
WScript.Echo " Successfully enabled WINS on all network adapters."
ElseIf intEnableWINS = 1 Then
WScript.Echo " Successfully enabled WINS on all network adapters." & _
VbCrLf & " Must reboot."
Else
WScript.Echo " Unable to enable WINS."
End If
WScript.Echo VbCrLf & String(80, "-")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>wins-enable.vbs
Host Name: .
Attempting to enable WINS
Successfully enabled WINS on all network adapters.
--------------------------------------------------------------------------------
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
DNS Enabled For WINS Resolution: True
WINS Enable LMHosts Lookup: True
WINS Host Lookup File:
WINS Scope ID: WORKGROUP
Top of page
Setting WINS Servers for a ClientIf NetBIOS is enabled independently of DHCP, you must assign IP addresses for a primary server and
optionally, for a secondary WINS server, as well as enabling WINS.
Win32_NetworkAdapterConfiguration offers the SetWINSServer method to assign WINS servers to a
client.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 42 assigns primary and secondary WINS servers to a client.
SetWINSServer is a static method, which means that it applies to all instances of the class (in this
case, all network adapters).
1. Create a variable to specify the computer name.
2. Create two variables to specify the IP addresses of the primary and secondary WINS servers, to
be passed to the EnableWINS method.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. Call the Get method on the Win32_NetworkAdapterConfiguration class.
This returns an object reference to the Win32_NetworkAdapterConfiguration class itself, rather
than a collection of its instances. This reference to the class must be used to call the static
method SetWINSServer.
5. Display the name of the computer.
6. Call the static method SetWINSServer of Win32_NetworkAdapterConfiguration, passing it the
two parameters defined above.
7. Check the value returned by the method, and display a success or error message.
8. Use the ExecQuery method to requery the Win32_NetworkAdapterConfiguration class, filtering
the WQL query with “WHERE IPEnabled = True.”
9. Display the IP addresses of the WINS servers that have been configured with the
SetWINSServer method.
Listing 42 Wins-setservers.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
On Error Resume Next
strComputer = "."
strWINSPrimaryServer = "192.168.0.1"
strWINSSecondaryServer = "192.168.0.2"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "Host Name: " & strComputer & VbCrLf & _
" Attempting to set WINS primary and secondary servers ..."
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & _
" Network Adapter " & objNicConfig.Index & VbCrLf & _
" " & objNicConfig.Description
intSetWINSServer = objNicConfig.SetWINSServer(strWINSPrimaryServer, _
strWINSSecondaryServer)
If intSetWINSServer = 0 Then
WScript.Echo " Successfully set WINS servers."
ElseIf intSetWINSServer = 1 Then
WScript.Echo " Successfully set WINS servers." & _
VbCrLf & " Must reboot."
Else
WScript.Echo " Unable to set WINS servers."
End If
Next
WScript.Echo VbCrLf & String(80, "-")
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>wins-setservers.vbs
Host Name: .
Attempting to set WINS primary and secondary servers ...
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
Successfully set WINS servers.
--------------------------------------------------------------------------------
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
Primary WINS Server: 192.168.0.1
Secondary WINS Server: 192.168.0.2
Top of page
Scenario: Preparing a Client for WINSTo configure WINS on a client, you must first decide whether and how NetBIOS is to be enabled. If
NetBIOS is disabled, you cannot use WINS. If NetBIOS is enabled by means of DHCP, the client can
get the correct settings from the DHCP server. If NetBIOS is enabled independent of DHCP, however,
you must enable WINS and assign primary and secondary WINS servers.
You can easily expand this script to run against multiple clients by using techniques demonstrated
in the "Scripting Remote Network Management" section of this paper.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 43 allows you to configure settings for NetBIOS and WINS in a change block near the
beginning. It first sets the mode of NetBIOS over TCP/IP on each network adapter. Then, if NetBIOS
is enabled but not by means of DHCP, the script enables WINS, configures WINS settings, and sets
the IP addresses of the WINS servers for the client to use.
1. Define constants to represent the three possible values of the TcpipNetbiosOptions property.
2. Create a variable to specify the computer name.
3. Create variables to specify the parameters to be passed to the EnableWINS method.
4. Create variables to specify the IP addresses of the primary and secondary WINS servers to be
passed to the EnableWINS method.
5. Initialize two Boolean flag variables to False.
6. Connect to the WMI service.
7. Call the GetSettings subroutine, which retrieves current NetBIOS and WINS settings.
8. Call the SetNetbios function, which sets the NetBIOS over TCP/IP mode to the value specified
in the intNetbiosTcpipSet variable.
9. If the resulting NetBIOS over TCP/IP setting is ENABLE_NETBIOS, call the SetWins function.
If it is ENABLE_NETBIOS_VIA_DHCP or DISABLE_NETBIOS, the script does not configure WINS
settings.
10. After making any changes in NetBIOS or WINS settings, again call the GetSettings subroutine.
11. The GetSettings subroutine retrieves and displays the values for all NetBIOS or WINS settings.
12. The SetNetbios function checks the current setting of the TcpipNetbiosOptions property. If the
property is not the same as the setting specified in the intNetbiosTcpipSet variable,
SetNetbios changes the setting to the value of intNetbiosTcpipSet. The function returns a
value of True if the NetBIOS over TCP/IP value has been set, and False if the value was not
set.
13. The SetWins function first calls the EnableWINS method, using the parameters specified in the
variables set at the beginning of the script. The function then calls the SetWINSServer method
with parameters specifying the IP addresses of the primary and secondary WINS servers. The
function returns a value of True if both EnableWINS and SetWINSServer returned a value of 0,
and False if either method returned a value other than 0.
Listing 43 Wins-client.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
On Error Resume Next
Const ENABLE_NETBIOS_VIA_DHCP = 0
Const ENABLE_NETBIOS = 1
Const DISABLE_NETBIOS = 2
strComputer = "."
blnDNSEnabledForWINSResolution = True
blnWINSEnableLMHostsLookup = True
strWINSHostLookupFile = ""
strWINSScopeID = "WORKGROUP"
strWINSPrimaryServer = "192.168.0.1"
strWINSSecondaryServer = "192.168.0.2"
intNetbiosTcpipSet = ENABLE_NETBIOS
blnNetbiosSet = False
blnWinsSet = False
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
WScript.Echo VbCrLf & "Host Name: " & strComputer
WScript.Echo VbCrLf & "NetBIOS and WINS settings before:"
GetSettings
WScript.Echo VbCrLf & String(80, "-")
blnNetbiosSet = SetNetbios
If blnNetbiosSet = True Then
Select Case intNetbiosTcpipSet
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>wins-client.vbs
Host Name: .
NetBIOS and WINS settings before:
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
NetBIOS Over TCP/IP: Disable NetBIOS over TCP/IP
DNS Enabled For WINS Resolution: True
WINS Enable LMHosts Lookup: False
WINS Host Lookup File:
WINS Scope ID: WORKGROUP
Primary WINS Server:
Secondary WINS Server:
--------------------------------------------------------------------------------
Network Adapter 1
Attempting to set NetBIOS Over TCI/IP value.
Successfully set NetBIOS over TCP/IP value.
NetBIOS over TCP/IP enabled.
Setting WINS parameters ...
Attempting to enable WINS ...
Successfully enabled WINS on all network adapters.
Attempting to set WINS primary and secondary servers ...
Network Adapter 1
Successfully set WINS servers.
All WINS parameters set.
--------------------------------------------------------------------------------
NetBIOS and WINS settings after:
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
NetBIOS Over TCP/IP: Enable NetBIOS over TCP/IP
DNS Enabled For WINS Resolution: True
WINS Enable LMHosts Lookup: True
WINS Host Lookup File:
WINS Scope ID: WORKGROUP
Primary WINS Server: 192.168.0.1
Secondary WINS Server: 192.168.0.2
Top of page
Tools for Scripting WINS on ClientsTable 23 outlines the available Windows tools to use for scripting WINS on clients.
Table 23 Tools for Scripting WINS on Clients
Technology Tool Where AvailableCommand-line
tools
Netsh.exe Windows operating systems1
Command-line
tools
NETWINSCONFIG.PL Windows 2000 Resource Kit
Command-line
tools
Wins.dll: WINS Replication Network Monitor
Parser
Windows Server 2003 Support Tools
Command-line
tools
Winschk.exe Windows 2000 Resource Kit
Command-line
tools
Winscl.exe: WINS Administration Tool Windows 2000 Resource Kit
WSH None
WMI Win32_NetworkAdapterConfiguration
1 Windows 2000, Windows XP, and Windows Server 2003. May also be present on other versions of Windows.
Table 24 outlines the available registry subkeys to use for scripting WINS on clients.
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 24 Registry Subkeys Related to Scripting WINS on Clients
Registry SubkeysHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\Adapter Identifier
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBIOS
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBT\Parameters
Automating TCP/IP Networking on ClientsPart 7: Scripting Other Network Protocols
Published: July 12, 2004This section demonstrates how to use WMI to script the management of a variety of TCP/IP and
related protocols on clients: TCP/IP filtering; ARP, IP, and TCP settings relating to routing;
Internetwork Packet Exchange (IPX) settings; and enumeration of network protocols running on
hosts. The sample scripts demonstrate more properties and methods of the
Win32_NetworkAdapterConfiguration class and introduce a new WMI class, Win32_NetworkProtocol.
This section provides scripting steps and sample scripts for these protocol-related tasks:
• Managing TCP/IP filtering settings.
• Managing other TCP/IP settings.
This includes subsections about managing and retrieving ARP settings, TCP settings, and IP packet
settings.
• Managing IPX.
• Enumerating the network protocols on a computer.
On This Page
Managing TCP/IP Filtering Settings
Managing Other TCP/IP Settings
Managing IPX
Enumerating the Network Protocols on a Computer
Tools for Scripting Other Network Protocols
Managing TCP/IP Filtering SettingsAs network security threats, such as viruses and worms, have gained notoriety, Internet Protocol
security (IPSec) has achieved increasing acceptance as an integrated set of interoperable,
cryptographically-based security services for traffic in the network layer between TCP/IP nodes. For
information about the base architecture of IPSec, see Internet Engineering Task Force RFC 2401,
"Security Architecture for the Internet Protocol," at http://go.microsoft.com/fwlink/?LinkId=24797.
WMI enables scripting the retrieval and configuration of TCP/IP client settings relating to one aspect
of IPSec, TCP/IP filtering, through several properties and methods of the
Win32_NetworkAdapterConfiguration class.
The first step in implementing TCP/IP filtering with WMI is to turn on filtering. To do this, you set the
IPFilterSecurityEnabled property to True by using the EnableIPFilterSec method. After TCP/IP filtering
is enabled, you can specify the TCP and User Datagram Protocol (UDP) ports to filter, and permit or
exclude specific protocols over IP. For more information about TCP/IP filtering, see the WMI SDK
topics about the EnableIPSec and EnableIPFilterSec methods of Win32_NetworkAdapterConfiguration
at http://go.microsoft.com/fwlink/?LinkId=29991.
Caution
Before changing these settings, make sure that the new configuration is consistent with your
network's implementation of TCP/IP filtering, IPSec, and overall network security. Always test such
changes on a test network before making them in a production environment.
Note that the two TCP/IP filtering methods, EnableIPSec and EnableIPFilterSec, do not follow the
division of functionality between "IP security" and "TCP/IP filtering," the two settings listed on the
Options tab of the Advanced TCP/IP Settings dialog box in Windows 2000. In Windows XP and
Windows Server 2003, only one option, "TCP/IP filtering," is listed on the Options tab, as Figure 13
illustrates.
Figure 13 Managing TCP/IP Filtering by Using the Windows Interface
See full-sized image
This section first presents two sample scripts that show you how to use these methods separately.
Then the section provides a third script that combines the methods to show how to enable TCP/IP
filtering and specify port and protocol filtering within the same script, as administrators might often
want to do. The script first tests whether TCP/IP filtering is enabled, and if it is not, enables it. It then
sets filters that grant access for only the specified TCP and UDP ports, and IP protocols.
Table 25 describes the TCP/IP filtering properties for the Win32_NetworkAdapterConfiguration class.
Table 25 TCP/IP Filtering Properties for the Win32_NetworkAdapterConfiguration Class
Property Type DescriptionIPFilterSecurityEnabled Boolean If TRUE, IP port security is enabled globally across all IP-bound
network adapters and the security values associated with
individual network adapters are in effect. This property is used in
conjunction with IPSecPermitTCPPorts, IPSecPermitUDPPorts, and
IPSecPermitIPProtocols. If FALSE, IP filter security is disabled
across all network adapters and allows all port and protocol traffic
to flow unfiltered.
IPSecPermitIPProtocols String
array
Array of the protocols permitted to run over the IP. The list of
protocols is defined using the EnableIPSec method. The list will
either be empty or contain numeric values. A numeric value of 0
(zero) indicates access permission is granted for all protocols. An
empty string indicates that no protocols are permitted to run
when IPFilterSecurityEnabled is TRUE.
IPSecPermitTCPPorts String Array of the ports that will be granted access permission for TCP.
Property Type Descriptionarray The list of protocols is defined using the EnableIPSec method. The
list will either be empty or contain numeric values. A numeric
value of 0 (zero) indicates access permission is granted for all
ports. An empty string indicates that no ports are granted access
permission when IPFilterSecurityEnabled is TRUE.
IPSecPermitUDPPorts String
array
Array of the ports that will be granted User Datagram Protocol
(UDP) access permission. The list of protocols is defined using the
EnableIPSec method. The list will either be empty or contain
numeric values. A numeric value of 0 (zero) indicates access
permission is granted for all ports. An empty string indicates that
no ports are granted access permission when
IPFilterSecurityEnabled is TRUE.
All the properties in the previous table are read-only.
Table 26 outlines the TCP/IP filtering methods and parameters for
Win32_NetworkAdapterConfiguration.
Table 26 Win32_NetworkAdapterConfiguration TCP/IP Filtering Methods
Method Parameters DescriptionEnableIPFilterSec IPFilterSecurityEnabled -
Boolean
Static method. Enables TCP/IP filtering globally across
all IP-bound network adapters. With security enabled,
the operational security characteristics for any one
network adapter can be controlled by using the
network adapter-specific EnableIPSec method.
EnableIPSec IPSecPermitTCPPorts –
string array
IPSecPermitUDPPorts –
string array
IPSecPermitIPProtocols –
string array
Enables TCP/IP filtering on a TCP/IP-enabled network
adapter. Ports are secured only when the
IPFilterSecurityEnabled property in
Win32_NetworkAdapterConfiguration is True.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that a problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
The Ipseccmd.exe command-line tool and the netsh ipsec command provide more extensive
functionality for working with many aspects of IPSec.
Displaying TCP/IP Filtering SettingsTo retrieve TCP/IP filtering settings, Win32_NetworkAdapterConfiguration provides several
properties that are network adapter-specific. IPFilterSecurityEnabled, however, is a global property
that applies to all IP-enabled network adapters. Note that IPFilterSecurityEnabled has replaced the
obsolete IPPortSecurityEnabled.
The properties IPSecPermitIPProtocols, IPSecPermitTCPPorts, and IPSecPermitUDPPorts all return
arrays of strings representing the ports or protocols that have been granted access permission. For
each, "0" indicates that access permission is granted for all protocols or ports, while an empty string
indicates that access permission is not granted for any ports.
Scripting Steps
Listing 44 displays TCP/IP filtering settings on all installed network adapters by using the properties
of Win32_Network AdapterConfiguration.
1. Create a variable and assign the name of a computer to it. For the local computer, simply
specify "." as the computer name. To run this script remotely, specify the name of an
accessible remote computer on your network on which you have administrative privileges. The
name can be in the form of either a host name or an IP address.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. 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.
4. For each network adapter configuration in the collection, display the index number, description,
and value for the IPFilterSecurityEnabled property.
5. If the IPSecPermitIPProtocols, IPSecPermitTCPPorts, and IPSecPermitUDPPorts properties are
not null, iterate through the arrays they return and display their values.
Listing 44 Ipfiltersettings.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNicConfig = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
For Each objNicConfig in colNicConfig
WScript.Echo VbCrLf & "Network Adapter " & objNicConfig.Index & _
VbCrLf & " " & objNicConfig.Description
WScript.Echo " IP Filter Security Enabled: " & _
objNicConfig.IPFilterSecurityEnabled
WScript.Echo " Protocols Permitted over IP:"
If Not IsNull(objNicConfig.IPSecPermitIPProtocols) Then
For Each strIPProtocol In objNicConfig.IPSecPermitIPProtocols
WScript.Echo " " & strIPProtocol
Next
End If
WScript.Echo " TCP Ports Permitted:"
If Not IsNull(objNicConfig.IPSecPermitTCPPorts) Then
For Each strTCPPort In objNicConfig.IPSecPermitTCPPorts
WScript.Echo " " & strTCPPort
Next
End If
WScript.Echo " UDPPorts Permitted:"
If Not IsNull(objNicConfig.IPSecPermitUDPPorts) Then
For Each strUDPPort In objNicConfig.IPSecPermitUDPPorts
WScript.Echo " " & strUDPPort
Next
End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ipfiltersettings.vbs
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packet
Scheduler Miniport
IP Filter Security Enabled: False
Protocols Permitted over IP:
0
TCP Ports Permitted:
0
UDPPorts Permitted:
0
Enabling TCP/IP Filtering by Using EnableIPFilterSec The class static method used in this script, EnableIPFilterSec, enables TCP/IP filtering globally across
all IP-enabled network adapters. After you enable TCP/IP filtering on all network adapters, you can
configure specific TCP/IP filtering settings for each one with the EnableIPSec method.
EnableIPFilterSec is a class static method that applies to all instances of the
Win32_NetworkAdapterConfiguration class, which is to say, all network adapters. This means that
you can use the Get() method of the SwbemServices object to get the
Win32_NetworkAdapterConfiguration class, rather than use the ExecQuery() method to get the
instances of the class. Instead of simply calling the method without parameters, like you do with
EnableDHCP, you have to pass it a Boolean value (True or False) for the IPFilterSecurityEnabled
property.
If your script calls only static methods, you can use more compact ways of binding to the
Win32_NetworkAdapterConfiguration class. For example, you might use either of the following lines:
Set objNicConfig = GetObject("winmgmts:\\" & strComputer & _
"\root\cimv2:Win32_NetworkAdapterConfiguration")
Set objNicConfig = GetObject("winmgmts:").Get _
("Win32_NetworkAdapterConfiguration")
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 45 enables IP filter security for all installed network adapters by using the EnableIPFilterSec
method of Win32_Network AdapterConfiguration. This method sets the IPFilterSecurityEnabled
property to True. IP filter security is called TCP/IP Filtering on the Options tab of the Advanced TCP/IP
dialog box.
1. Create a variable to specify the computer name.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the static Get method of the SWbemServices object to get an SWbemObject representing
the Win32_NetworkAdapterConfiguration class.
Changes made to this object apply to all network adapters on the computer.
4. Call the EnableIPFilterSec static method of Win32_NetworkAdapterConfiguration, passing it a
Boolean parameter of True.
5. Check the value returned by the method, and display a success or error message.
Listing 45 Ipfilter-enableipfilter.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objNicConfig = objWMIService.Get("Win32_NetworkAdapterConfiguration")
If Not objNicConfig.IPFilterSecurityEnabled Then
intFilterReturn = objNicConfig.EnableIPFilterSec(True)
If intFilterReturn = 0 Then
WScript.Echo "IP Filtering enabled for all network adapters."
ElseIf intFilterReturn = 1 Then
WScript.Echo "IP Filtering enabled for all network adapters." & _
VbCrLf & "Must reboot for changes to take effect."
Else
WScript.Echo "Unable to enable IP Filtering."
End If
Else
WScript.Echo "IP Filtering already enabled."
End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ipfilter-enableipfilter.vbs
IP Filter Security Enabled:
IP Filtering enabled for all network adapters.
Must reboot for changes to take effect.
Implementing TCP/IP Filtering by Using EnableIPSecAfter you enable TCP/IP filtering by using EnableIPFilterSec, you can use the EnableIPSec method to
grant access permission to TCP and UDP traffic on specific ports and deny access on others. You can
also permit or exclude protocols to run over IP. The EnableIPSec method makes these specific
security choices for each network adapter.
Note that the EnableIPSec and EnableIPFilterSec methods reverse the functionality of "IP security"
and "TCP/IP filtering," the two settings listed in the Advanced TCP/IP Settings dialog box in
Windows 2000. In Windows XP and Windows Server 2003, the two settings are merged into one
option, TCP/IP filtering, on the Options tab.
The Properties button on the Options tab enables you to open the TCP/IP Filtering dialog box, which
includes a check box for "Enable TCP/IP Filtering (All adapters)" and separate settings for TCP ports,
UDP ports, and IP protocols. For each of these options, you can choose either "Permit All" or "Permit
Only," which enables you to specify the ports or protocols to be permitted.
Scripting Steps
Listing 46 enables IP filter security on specific network adapters by using the EnableIPSec method.
This script grants access permission to all TCP, UDP, and IP ports.
Important
Before running this script, you must set the IPFilterSecurityEnabled property to True by using the
EnableIPFilterSec method of Win32_Network AdapterConfiguration. For information about
performing this step, see “Enabling TCP/IP Filtering by Using EnableIPFilterSec” earlier in this paper.
For the three parameters of EnableIPSec, IPSecPermitIPProtocols, IPSecPermitTCPPorts, and
IPSecPermitUDPPorts, a value of 0 indicates that access permission is granted for all protocols or
ports and a null value (an empty array) indicates that access permission is not granted for any
protocols or ports. Otherwise, IPSecPermitTCPPorts and IPSecPermitUDPPorts must be arrays of
strings representing the ports to be granted access; IPSecPermitIPProtocols must be an array of
strings representing the permitted protocols.
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
1. Define a constant for allowing all ports and protocols.
2. Create a variable to specify the computer name.
3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. 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.
5. For each network adapter configuration in the collection, perform the following tasks.
6. Assign the ALLOW_ALL constant to arrays of permitted TCP ports, permitted UDP ports, and
permitted IP protocols, to be passed as parameters.
The script can be modified to specify only certain ports and protocols.
7. Call the EnableIPSec method of Win32_NetworkAdapterConfiguration, passing it the arrays of
permitted TCP ports, permitted UDP ports, and permitted IP protocols.
8. Check the value returned by the method, and display a success or error message.
Listing 46 Ipfilter-enableipsec.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
On Error Resume Next
Const ALLOW_ALL = 0
arrPermittedTCPPorts = Array(ALLOW_ALL)
arrPermittedUDPPorts = Array(ALLOW_ALL)
arrPermittedIPProtocols = Array(ALLOW_ALL)
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNicConfig = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
For Each objNicConfig in colNicConfig
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
If objNicConfig.IPFilterSecurityEnabled Then
intIPSecReturn = objNicConfig.EnableIPSec(arrPermittedTCPPorts, _
arrPermittedUDPPorts, arrPermittedIPProtocols)
If intIPSecReturn = 0 Then
WScript.Echo " IP Filtering enabled for specified ports and protocols."
ElseIf intIPSecReturn = 1 Then
WScript.Echo " IP Filtering enabled for specified ports and protocols." _
& VbCrLf & " Must reboot for changes to take effect."
Else
WScript.Echo " Unable to enable IP Filtering for " & _
"specified ports and protocols."
End If
Else
WScript.Echo " IP Filtering not enabled. Must enable before " & _
"specifying port and protocols."
End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ipfilter-enableipsec.vbs
Network Adapter 1
IP Filtering enabled for specified ports and protocols.
Must reboot for changes to take effect.
Enabling and Implementing TCP/IP Filtering in a Single ScriptThis script combines techniques from the previous two sections to show how to combine the
EnableIPFilterSec and EnableIPSec methods to enable TCP/IP filtering and configure specifics on all
network adapters.
The script first tests for whether TCP/IP filtering is enabled and, if not, it calls EnableIPFilterSec. It
then sets permitted TCP and UDP ports, and IP protocols.
For simplicity, this script is designed to set the same EnableIPSec parameters for each network
adapter; a more complex script could set different settings for specific network adapters.
The script defines two constants that will be passed as parameters to EnableIPSec.
• The value of ALLOW_ALL is a string containing the number 0, which allows all ports or protocols.
This constant is passed to EnableIPSec as the parameter for permitted UDP ports.
• The value of ALLOW_NONE is an empty string (""), which denies permission to all ports or protocols.
This constant is passed to EnableIPSec as the parameter for permitted IP protocols.
For permitted TCP ports, the script directly passes two literal string values, “80” and “443,” to the
method.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
1. Define constants for allowing all ports and protocols (0) and for allowing none (an empty
string).
2. Create a constant for the value that will allow all traffic and a variable to specify the computer
name.
3. Set the Boolean variable representing the state of the IPFilterSecurityEnabled property to
False.
4. Assign ports 80 and 443 to the array of permitted TCP ports.
5. Assign the ALLOW_NONE constant to the array of permitted UDP ports.
6. Assign the ALLOW_ALL constant to the arrays of permitted IP protocols.
7. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
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. Iterate through the collection of network adapters, displaying current TCP/IP filtering settings.
10. If the IPFilterSecurityEnabled property is set to False, call the static Get method of the
SWbemServices object to get an SWbemObject representing the
Win32_NetworkAdapterConfiguration class.
Changes made to this object apply to all network adapters on the computer.
11. Call the EnableIPFilterSec method of Win32_NetworkAdapterConfiguration on the class object
reference, passing it a parameter of True.
12. Check the value returned by the method, and display a success or error message.
13. Requery the Win32_NetworkAdapterConfiguration class with the ExecQuery method, filtering
the WQL query with “WHERE IPEnabled = True.”
14. Iterate through the collection of network adapters again, calling the EnableIPSec method of
Win32_NetworkAdapterConfiguration on each, and passing it the arrays of permitted TCP
ports, permitted UDP ports, and permitted IP protocols.
15. Check the value returned by the method, and display a success or error message.
16. Requery the Win32_NetworkAdapterConfiguration class with the ExecQuery method, filtering
the WQL query with “WHERE IPEnabled = True.”
17. Iterate through the collection of network adapters, displaying TCP/IP filtering settings
including any changes.
Listing 47 Ipfilter-enable.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
On Error Resume Next
Const ALLOW_ALL = "0"
Const ALLOW_NONE = ""
strComputer = "."
blnIPFilterSecurityEnabled = "False"
arrPermittedTCPPorts = Array("80", "443")
arrPermittedUDPPorts = Array(ALLOW_NONE)
arrPermittedIPProtocols = Array(ALLOW_ALL)
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNicConfig = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
WScript.Echo VbCrLf & "Settings Before Enabling IP Filtering"
For Each objNicConfig in colNicConfig
blnIPFilterSecurityEnabled = objNicConfig.IPFilterSecurityEnabled
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & VbCrLf & _
" IP Filtering Enabled: " & blnIPFilterSecurityEnabled
WScript.Echo " TCP Ports:"
If Not IsNull(objNicConfig.IPSecPermitTCPPorts) Then
For Each strTCPPort In objNicConfig.IPSecPermitTCPPorts
WScript.Echo " " & strTCPPort
Next
End If
WScript.Echo " UDP Ports:"
If Not IsNull(objNicConfig.IPSecPermitUDPPorts) Then
For Each strUDPPort In objNicConfig.IPSecPermitUDPPorts
WScript.Echo " " & strUDPPort
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ipfilter-enable.vbs
Settings Before Enabling IP Filtering
Network Adapter 1
IP Filtering Enabled: False
TCP Ports:
0
UDP Ports:
0
IP Protocols:
0
Enabling IP Filtering ...
IP Filtering enabled for all network adapters.
Must reboot for changes to take effect.
Filters enabled on 1 for specified ports and protocols.
Must reboot for changes to take effect.
Settings After Enabling IP Filtering
Network Adapter 1
IP Filtering Enabled: True
TCP Ports:
80
443
UDP Ports:
IP Protocols:
0
Disabling TCP/IP FilteringIf you need to disable TCP/IP filtering on a network segment or another group of hosts, using
scripting for those tasks on multiple computers can save administrative time. In certain situations
on individual hosts, too, such as a laptop that is frequently moved between a network that uses
TCP/IP filtering to one that does not, a script that disables TCP/IP filtering from the command prompt
might be useful.
Scripting Steps
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Listing 48 disables TCP/IP filtering for each IP-enabled network adapter setting.
1. Create a constant for the value that will allow all traffic and a variable to specify the computer
name.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. 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.
4. For each network adapter configuration in the collection, perform the following tasks.
5. Display the current TCP/IP filtering settings.
6. Call the DisableIPSec method of Win32_NetworkAdapterConfiguration.
7. Check the value returned by the method, and display a success or error message.
8. Requery the Win32_NetworkAdapterConfiguration class with the ExecQuery method, filtering
the WQL query with “WHERE IPEnabled = True.”
9. Iterate through the collection of network adapters, displaying TCP/IP filtering settings including
any changes.
Listing 48 Ipfilter-disable.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colNicConfig = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
WScript.Echo VbCrLf & "IPSec and TCP/IP Filtering Settings"
For Each objNicConfig in colNicConfig
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index & _
VbCrLf & " IP Filtering Enabled: " & _
objNicConfig.IPFilterSecurityEnabled
WScript.Echo " TCP Ports:"
If Not IsNull(objNicConfig.IPSecPermitTCPPorts) Then
For Each strTCPPort In objNicConfig.IPSecPermitTCPPorts
WScript.Echo " " & strTCPPort
Next
End If
WScript.Echo " UDP Ports:"
If Not IsNull(objNicConfig.IPSecPermitUDPPorts) Then
For Each strUDPPort In objNicConfig.IPSecPermitUDPPorts
WScript.Echo " " & strUDPPort
Next
End If
WScript.Echo " IP Protocols:"
If Not IsNull(objNicConfig.IPSecPermitIPProtocols) Then
For Each strIPProtocol In objNicConfig.IPSecPermitIPProtocols
WScript.Echo " " & strIPProtocol
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ipfilter-disable.vbs
IPSec and TCP/IP Filtering Settings
Network Adapter 1
IP Filtering Enabled: True
TCP Ports:
80
443
UDP Ports:
IP Protocols:
0
IP Filtering disabled.
Must reboot for changes to take effect.
Settings After Operation
Network Adapter 1
IP Filtering Enabled: True
TCP Ports:
0
UDP Ports:
0
IP Protocols:
0
Top of page
Managing Other TCP/IP SettingsThe Win32_NetworkAdapterConfiguration class exposes numerous other properties and methods
relating to Address Resolution Protocol (ARP), Transmission Control Protocol (TCP), and Internet
Protocol (IP) settings. Because most of these properties are primarily used to configure routing or for
advanced network performance tuning, this paper does not cover them in much detail. However,
they are listed in the following tables, and a script that displays the property settings for each
protocol is shown below.
For each read-only property, there is a corresponding method to change it, but no example script is
shown for the methods. If a computer is not configured for routing, these properties often return an
empty value or Null.
For information about how to use a few of these settings to improve network performance, see the
section “Performance Tuning for Networking” in “Performance Tuning Guidelines for Windows
Server 2003” at http://go.microsoft.com/fwlink/?LinkId=24798.
Managing ARP SettingsAddress Resolution Protocol (ARP) is the protocol that maps IP addresses to physical (MAC)
addresses. Windows includes the command-line tool Arp.exe that can list and configure ARP cache
entries.
Table 27 describes the Win32_NetworkAdapterConfiguration properties that work with ARP.
Table 27 ARP Properties for the Win32_NetworkAdapterConfiguration Class
Property Type DescriptionArpAlwaysSourceRoute Boolean If True, TCP/IP transmits Address Resolution Protocol (ARP)
queries with source routing enabled on Token Ring networks.
By default (False), ARP first queries without source routing, and
then retries with source routing enabled if no reply is received.
Source routing allows the routing of network packets across
different types of networks.
ArpUseEtherSNAP Boolean If True, Ethernet packets follow the IEEE 802.3 Sub-Network
Access Protocol (SNAP) encoding. Setting this parameter to 1
forces TCP/IP to transmit Ethernet packets by using 802.3 SNAP
encoding.
By default (False), the stack transmits packets in DIX Ethernet
format. Windows NT and Windows 2000 systems can receive both
formats.
All the properties in the previous table are read-only.
Table 28 describes the Win32_NetworkAdapterConfiguration methods that work with ARP.
Table 28 ARP Methods for the Win32_NetworkAdapterConfiguration Class
Method Parameters DescriptionSetArpAlwaysSourceRoute ArpAlwaysSourceRoute –
Boolean
Static method. Sets the transmission of ARP
queries by the TCP/IP.
If the parameter is True, TCP/IP is forced to
transmit ARP queries with source routing
enabled on Token Ring networks.
By default, the stack transmits ARP queries
without source routing first, then retries with
source routing enabled if no reply is received.
SetArpUseEtherSNAP ArpUseEtherSNAP –
Boolean
Static method. Enables TCP/IP to transmit
Ethernet packets using 802.3 SNAP encoding.
If the parameter is True, Ethernet packets use
802.3 SNAP encoding.
By default, the stack transmits packets in
Digital, Intel, Xerox (DIX) Ethernet format. It
always receives both formats.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that some problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
Managing TCP SettingsTable 29 describes the Win32_NetworkAdapterConfiguration properties that work with TCP settings.
Table 29 Win32_NetworkAdapterConfiguration TCP Properties
Property Type DescriptionKeepAliveInterval Uint32
Units:
Milliseconds
Interval separating Keep Alive Retransmissions until
a response is received. After a response is received,
the delay until the next Keep Alive Transmission is
again controlled by the value of KeepAliveTime. The
connection will be aborted after the number of
retransmissions specified by
TcpMaxDataRetransmissions have gone unanswered.
Default: 1000, Valid Range:
1–xFFFFFFFF.
KeepAliveTime Uint32
Units:
Milliseconds
Indicates how often the TCP attempts to verify that
an idle connection is still intact by sending a Keep
Alive Packet. A remote system that is reachable will
acknowledge the keep alive transmission. Keep Alive
packets are not sent by default. This feature may be
enabled in a connection by an application. Default:
7,200,000 (two hours)
MTU Uint32
Units: Bytes
Overrides the default Maximum Transmission Unit
(MTU) for a network interface. The MTU is the
maximum packet size (including the transport
header) that the transport will transmit over the
underlying network. The IP datagram can span
multiple packets. The range of this value spans the
minimum packet size (68) to the MTU supported by
the underlying network.
PMTUBHDetectEnabled Boolean If TRUE, detection of black hole routers occurs while
TCP discovers the path of the Maximum Transmission
Unit. A black hole router does not return ICMP
Destination Unreachable messages when it needs to
fragment an IP datagram with the Don't Fragment bit
set. TCP depends on receiving these messages to
perform Path MTU Discovery. With this feature
enabled, TCP will try to send segments without the
Don't Fragment bit set if several retransmissions of a
segment go unacknowledged. If the segment is
acknowledged as a result, the MSS will be decreased
and the Don't Fragment bit will be set in future
packets on the connection. Enabling black hole
detection increases the maximum number of
retransmissions performed for a given segment. The
default value of this property is FALSE.
PMTUDiscoveryEnabled Boolean If TRUE, the Maximum Transmission Unit (MTU) path
is discovered over the path to a remote host. By
discovering the MTU path and limiting TCP segments
to this size, TCP can eliminate fragmentation at
routers along the path that connect networks with
different MTUs. Fragmentation adversely affects TCP
Property Type Descriptionthroughput and network congestion. Setting this
parameter to FALSE causes an MTU of 576 bytes to
be used for all connections that are not to machines
on the local subnet. The default is TRUE.
TcpMaxConnectRetransmissions Uint32 Number of times TCP attempts to retransmit a
Connect Request before terminating the connection.
The initial retransmission time-out is 3 seconds. The
retransmission time-out doubles for each attempt.
Default: 3, Valid Range: 0–0xFFFFFFFF.
TcpMaxDataRetransmissions Uint32 Number of times TCP re-transmits an individual data
segment (non-connect segment) before terminating
the connection. The retransmission time-out doubles
with each successive retransmission on a connection.
Default: 5, Valid Range: 0–0xFFFFFFFF.
TcpNumConnections Uint32 Maximum number of connections that TCP can have
open simultaneously. Default: 0xFFFFFE, Valid
Range: 0–0xFFFFFE.
TcpUseRFC1122UrgentPointer Boolean If TRUE, TCP uses the RFC 1122 specification for
urgent data. If FALSE (default), TCP uses the mode
used by Berkeley Software Design (BSD) derived
systems. The two mechanisms interpret the urgent
pointer differently and are not interoperable.
Windows 2000 and Windows NT 3.51 and later
default to BSD mode.
TcpWindowSize Uint16
Units: Bytes
Maximum TCP Receive Window size offered by the
system. The Receive Window specifies the number of
bytes a sender may transmit without receiving an
acknowledgment. In general, larger receiving
windows will improve performance over high delay
and high bandwidth networks. For efficiency, the
receiving window should be an even multiple of the
TCP Maximum Segment Size (MSS). Default: Four
times the maximum TCP data size or an even
multiple of TCP data size rounded up to the nearest
multiple of 8192. Ethernet networks default to 8760.
Valid range: 0–5535.
All the properties in the previous table are read-only.
Table 30 describes the Win32_NetworkAdapterConfiguration methods that work with TCP settings.
Table 30 Win32_NetworkAdapterConfiguration TCP Methods
Method Parameters DescriptionSetKeepAliveInterval KeepAliveInterval – int32
Value, in milliseconds, for the
interval separating Keep Alive
Retransmissions until a
response is received.
Static method. Sets the interval
separating Keep Alive
Retransmissions until a response is
received. After a response is
received, the delay until the next
Method Parameters DescriptionKeep Alive Transmission is again
controlled by the value of the
KeepAliveTime property. The
connection is terminated after the
number of retransmissions
specified by the
TcpMaxDataRetransmissions
property have gone unanswered.
SetKeepAliveTime KeepAliveTime – uint32
Interval, in milliseconds, the
TCP waits to check that an idle
connection is still available.
Static method. Sets how often TCP
attempts to verify that an idle
connection is still available by
sending a Keep Alive packet. If the
remote system is still reachable
and functioning, it will
acknowledge the Keep Alive
transmission. Keep Alive packets
are not sent by default. This
feature may be enabled in a
connection by an application.
SetMTU
Windows Server 2003: This
method is not supported. No
replacement exists and the values
do not correspond to the intended
purpose of the method.
MTU – int32
Default Maximum Transmission
Unit (MTU) for a network
interface The range of this
value spans the minimum
packet size (68) to the MTU
supported by the underlying
network.
Static method. Sets the default
Maximum Transmission Unit (MTU)
for a network interface. The MTU is
the maximum packet size (in
bytes) that a transport will
transmit over the underlying
network. The size includes the
transport header.
Note that an IP datagram can span
multiple packets. Values larger
than the default for the underlying
network result in the transport
using the network default MTU.
Values smaller than 68 result in
the transport using an MTU of 68.
SetPMTUBHDetect PMTUBHDetectEnabled –
Boolean
If TRUE, TCP attempts to
discover black hole and route
packets in different network
paths.
Static method. Enables detection
of black hole routers while doing
Path MTU Discovery. A black hole
router does not return the Internet
Control Message Protocol (ICMP)
Destination Unreachable messages
when it needs to fragment an IP
datagram with the Don't Fragment
bit set. TCP depends on receiving
these messages to perform Path
MTU Discovery.
Method Parameters DescriptionWith this feature enabled, TCP will
try to send segments without the
Don't Fragment bit set if several
retransmissions of a segment go
unacknowledged. If the segment is
acknowledged as a result, the
maximum segment size (MSS) will
be decreased and the Don't
Fragment bit will be set in future
packets on the connection.
Enabling black hole detection
increases the maximum number of
retransmissions performed for a
given segment.
SetPMTUDiscovery PMTUDiscoveryEnabled –
Boolean
If TRUE, TCP is enabled to
attempt to discover the
Maximum Transmission Unit
(MTU) or largest packet size
over the path to a remote host.
The default is TRUE.
Static method. Enables Maximum
Transmission Unit (MTU) discovery
over the path to a remote host. By
discovering the Path MTU and
limiting TCP segments to this size,
TCP can eliminate fragmentation
at routers along the path that
connect networks with different
MTUs. Fragmentation adversely
affects TCP throughput and
network congestion. Setting this
parameter to FALSE causes an
MTU of 576 bytes to be used for all
connections that are not to
machines on the local subnet.
SetTcpMaxConnectRetransmissionsTcpMaxConnectRetransmissions
– int32
Number of attempts TCP will
retransmit a connect request
before aborting. The valid range
for values is 0–0xFFFFFFFF.
Static method. Sets the number of
attempts TCP will retransmit a
connect request before aborting.
The initial retransmission time-out
is 3 seconds, and doubles for each
attempt.
SetTcpMaxDataRetransmissions TcpMaxDataRetransmissions –
int32
Number of times TCP
retransmits an individual data
segment before aborting the
connection. Valid range: 0–
0xFFFFFFFF.
Static method. Sets the number of
times TCP retransmits an
individual data segment before
aborting the connection. The
retransmission time-out doubles
with each successive
retransmission on a connection.
SetTcpNumConnections TcpNumConnections – int32
Maximum number of
connections that TCP may have
open simultaneously. Valid
Static method. Sets the maximum
number of connections that TCP
may have open simultaneously.
Method Parameters Descriptionrange: 0–0xFFFFFE.
SetTcpUseRFC1122UrgentPointer TcpUseRFC1122UrgentPointer –
Boolean
If TRUE, TCP uses the RFC 1122
specification. If FALSE, urgent
data is sent in the mode used
by BSD-derived systems.
Static method. Specifies whether
TCP uses the RFC 1122
specification for urgent data, or
the mode used by Berkeley
Software Design (BSD) derived
systems. The two mechanisms
interpret the urgent pointer in the
TCP header and the length of the
urgent data differently. They are
not interoperable. Windows 2000
and Windows NT 3.51 or later
default to BSD mode.
SetTcpWindowSize TcpWindowSize – int16
Maximum TCP receive window
size (in bytes) offered by the
system. Valid range (in bytes):
0–65535.
Static method. Sets the maximum
TCP Receive Window size offered
by the system. The receive window
specifies the number of bytes a
sender can transmit without
receiving an acknowledgment. In
general, larger receive windows
improve performance over high
delay and high bandwidth
networks. For efficiency, the
receive window should be an even
multiple of the TCP Maximum
Segment Size (MSS).
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that some problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
Managing IP Packet SettingsTable 31 describes the Win32_NetworkAdapterConfiguration properties that work with Internet
Protocol (IP) settings.
Table 31 Win32_NetworkAdapterConfiguration IP Properties
Property Type DescriptionDefaultTOS Uint8 Default Type Of Service (TOS) value set in the header of outgoing IP
packets. Request for Comments (RFC) 791 defines the values.
Default: 0, Valid Range: 0–255.
DefaultTTL Uint8 Default Time To Live (TTL) value set in the header of outgoing IP
packets. The TTL specifies the number of routers an IP packet can
pass through to reach its destination before being discarded. Each
router decrements by one the TTL count of a packet as it passes
through and discards the packets—if the TTL is 0 (zero). Default: 32,
Property Type DescriptionValid Range: 1–255.
IPUseZeroBroadcast Boolean If TRUE, IP zeros-broadcasts are used (0.0.0.0), and the system uses
ones-broadcasts (255.255.255.255). Computer systems generally use
ones-broadcasts, but those derived from BSD implementations use
zeros-broadcasts. Systems that do not use the same broadcasts
cannot interoperate on the same network. The default is FALSE.
All the properties in the previous table are read-only.
Table 32 describes the Win32_NetworkAdapterConfiguration methods that work with IP settings.
Table 32 Win32_NetworkAdapterConfiguration IP Methods
Method Parameters DescriptionSetDefaultTOS
Obsolete. Applications
should use the QoS API to
manipulate TOS bits.
DefaultTOS – string
Parameter is Type of
Service (TOS) value put
in the header of
outgoing IP packets. For
a definition of the
values, see RFC 791.
Static method. Sets the default Type of Service
(TOS) value in the header of outgoing IP packets.
SetDefaultTTL DefaultTTL – uint 8
Parameter is the Time to
Live value set in the
header of outgoing IP
packets. Default: 32;
Valid range: 1–255
Static method. Sets the default Time to Live (TTL)
value in the header of outgoing IP packets. The TTL
specifies the number of routers an IP packet may
pass through to reach its destination before being
discarded. Each router decrements the TTL count
of a packet by one and discards the packets with a
TTL of 0.
SetIPUseZeroBroadcast IPUseZeroBroadcast –
Boolean
If TRUE, IP zero
broadcast is used. The
default is FALSE.
Static method. Set IP zero broadcast usage. If the
IPUseZeroBroadcast parameter is set to TRUE, then
IP will use zero-broadcasts (0.0.0.0) instead of one-
broadcasts (255.255.255.255). Most systems use
one-broadcasts, but systems derived from BSD
implementations use zero-broadcasts. Systems
that use different broadcasts will not interoperate
on the same network.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that some problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
Retrieving ARP, TCP, and IP Packet SettingsARP, TCP, and IP packet settings are typically used primarily on routers. Note that these properties
are often empty or null on computers not configured as routers.
Scripting Steps
Listing 49 retrieves and displays ARP, IP, and TCP packet settings.
1. Create a variable and assign the name of a computer to it. For the local computer, simply
specify "." as the computer name. To run this script remotely, specify the name of an
accessible remote computer on your network on which you have administrative privileges. The
name can be in the form of either a host name or an IP address.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. 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.
4. For each network adapter configuration in the collection, display the ARP, IP, and TCP
properties, each under its own heading.
Listing 49 Arp-ip-tcp-settings.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery("SELECT * FROM " & _
"Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
WScript.Echo VbCrLf & "ARP, IP and TCP packet settings"
WScript.Echo VbCrLf & "Host Name: " & strComputer
For Each objNicConfig in colNicConfigs
WScript.Echo VbCrLf & " Network Adapter: " & objNicConfig.Index & _
VbCrLf & " " & objNicConfig.Description
WScript.Echo VbCrLf & " ARP Settings:"
WScript.Echo " ARP queries use source routing on Token Ring: " & _
objNicConfig.ArpAlwaysSourceRoute
WScript.Echo " ARP uses SNAP encoding on Ethernet: " & _
objNicConfig.ArpUseEtherSNAP
WScript.Echo VbCrLf & " IP packet settings:"
WScript.Echo " Default Type Of Service: " & objNicConfig.DefaultTOS
WScript.Echo " Default Time To Live: " & objNicConfig.DefaultTTL
WScript.Echo " IP uses zeros-broadcasts: " & _
objNicConfig.IPUseZeroBroadcast
WScript.Echo VbCrLf & " TCP Settings:"
WScript.Echo " Keep Alive Interval: " & objNicConfig.KeepAliveInterval
WScript.Echo " Keep Alive Time: " & objNicConfig.KeepAliveTime
WScript.Echo " Maximum Transmission Unit: " & objNicConfig.MTU
WScript.Echo " Maximum Transmission Unit path discovery enabled: " & _
objNicConfig.PMTUDiscoveryEnabled
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>arp-ip-tcp-settings.vbs
ARP, IP and TCP packet settings
Host Name: .
Network Adapter: 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Packe
t Scheduler Miniport
ARP Settings:
ARP queries use source routing on Token Ring:
ARP uses SNAP encoding on Ethernet:
IP packet settings:
Default Type Of Service:
Default Time To Live:
IP uses zeros-broadcasts:
TCP Settings:
Keep Alive Interval:
Keep Alive Time:
Maximum Transmission Unit:
Maximum Transmission Unit path discovery enabled:
Maximum number of connect request retransmissions:
Maximum number of data segment retransmissions:
Maximum number of simultaneous open connections:
Use RFC 1122 specification for urgent data:
Maximum TCP receive window size:
Top of page
Managing IPXInternetwork Packet Exchange (IPX) is a protocol used by older Novell NetWare networks.
Win32_NetworkAdapterConfiguration provides a few properties and methods for IPX configuration,
which may be useful on networks that have both NetWare-based and Windows-based clients.
Table 33 describes the IPX properties for the Win32_NetworkAdapterConfiguration class.
Table 33 IPX Properties of the Win32_NetworkAdapterConfiguration Class
Property Type DescriptionIPXEnabled Boolean If TRUE, the IPX protocol is bound and enabled for this
adapter.
IPXAddress String IPX address of the network adapter. The IPX address
identifies a computer system on a network that uses the IPX
protocol.
IPXFrameType Uint32 array Array of frame type identifiers. The values in this array
Property Type Descriptioncorrespond to the elements in IPXNetworkNumber.
O = Ethernet II
1 = Ethernet 802.3
2 = Ethernet 802.2
3 = Ethernet SNAP
255 = AUTO
IPXMediaType Uint32 IPX media type identifier.
1 = Ethernet
2 = Token Ring
3 = FDDI
8 = ARCNET
IPXNetworkNumber String array Array of characters that uniquely identifies a frame/network
adapter combination on the computer system. The NWLink
IPX/SPX/NetBIOS Compatible Transport Protocol (NWLink) in
Windows 2000 and Windows NT 4.0 and later use two
distinctly different types of network numbers. This number is
sometimes referred to as the external network number. It
must be unique for each network segment. The order in this
string list will correspond item-for-item with the elements in
the IPXFrameType property.
IPXVirtualNetNumber String Unique identifier of the computer system on the network. It is
represented in the form of an eight-character hexadecimal
digit. Windows NT and Windows 2000 use the virtual network
number (also known as an internal network number) for
internal routing.
All the properties in the previous table are read-only.
Table 34 describes the IPX methods for the Win32_NetworkAdapterConfiguration class.
Table 34 IPX Methods for the Win32_NetworkAdapterConfiguration Class
Method Parameters DescriptionSetIPXFrameTypeNetworkPairs IPXNetworkNumber – string
array
Array of characters that
uniquely identify an adapter on
the computer system. The
NWLink in Windows 2000 and
Windows NT 3.51 or later uses
two different types of network
numbers. This number is
sometimes referred to as the
External Network Number. It
must be unique for each
network segment. The values
in this string list must have a
corresponding value in the
IPXFrameType parameter
Static method. Sets IPX network
number/frame pairs for this network
adapter. Windows 2000 and Windows
NT 3.51 or later use an IPX network
number for routing purposes. It is
assigned to each configured frame
type/network adapter combination on
your computer system. This number is
sometimes referred to as the external
network number. It must be unique for
each network segment. If the frame
type is set to AUTO, the network
number should to zero.
Method Parameters Descriptionidentifying the packet frame
type used for this network.
IPXFrameType - –int32 array
Integer array of frame type
identifiers. The values in this
array correspond to the
elements in the
IPXNetworkNumber parameter.
SetIPXVirtualNetworkNumber IPXNetworkNumber – string
array
Array of characters that
uniquely identify an adapter on
the computer system. The
NWLink in Windows 2000 and
Windows NT 3.51 or later uses
two different types of network
numbers. This number is
sometimes referred to as the
External Network Number. It
must be unique for each
network segment. The values
in this string list must have a
corresponding value in the
IPXFrameType parameter
identifying the packet frame
type used for this network.
IPXFrameType - –int32 array
Integer array of frame type
identifiers. The values in this
array correspond to the
elements in the
IPXNetworkNumber parameter.
Static method. Sets the IPX virtual
network number on the target
computer system. Windows 2000 and
Windows NT 3.51 or later use an
internal network number for internal
routing. The internal network number is
also known as a virtual network
number, which uniquely identifies the
computer system on the network.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• 1 indicates successful completion with reboot required.
• Numbers greater than 1 indicate that some problem was encountered and the method could not
complete. The WMI SDK lists the meanings of return values for these methods.
Scripting Steps
Listing 50 simply displays IPX-related properties; it does not configure any IPX settings. This script
uses the VBScript Select Case statement to handle multiple possibilities for a value, in this case
translating integers returned by the property into descriptive strings.
To carry out this task, the script must:
1. Create a variable to specify the computer name.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class.
This returns a collection consisting of all the network adapter configurations on the computer.
4. For each network adapter configuration in the collection, display the IPX properties.
5. Use Select Case statements to translate the integer values returned by the IPXFrameType and
IPXMediaType properties into descriptive strings.
Listing 50 Ipxsettings.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
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkAdapterConfiguration")
WScript.Echo VbCrLf & "IPX Settings"
For Each objNicConfig In colNicConfigs
WScript.Echo VbCrLf & " Network Adapter " & objNicConfig.Index
WScript.Echo " " & objNicConfig.Description
WScript.Echo " IPX Enabled: " & objNicConfig.IPXEnabled
If objNicConfig.IPXEnabled Then
WScript.Echo " IPX Address: " & objNicConfig.IPXAddress
WScript.Echo " IPX Network Number(s):"
If Not IsNull(objNicConfig.IPXNetworkNumber) Then
For Each strIPXNetworkNumber In objNicConfig.IPXNetworkNumber
WScript.Echo " " & strIPXNetworkNumber
Next
End If
WScript.Echo " IPX Virtual Network Number: " & _
objNicConfig.IPXVirtualNetNumber
WScript.Echo " IPX Frame Type(s):"
If Not IsNull(objNicConfig.IPXFrameType) Then
For Each intIPXFrameType In objNicConfig.IPXFrameType
Select Case intIPXFrameType
Case 0 strIPXFrameType = "Ethernet II"
Case 1 strIPXFrameType = "Ethernet 802.3"
Case 2 strIPXFrameType = "Ethernet 802.2"
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>ipxsettings.vbs
IPX Settings
Network Adapter 1
3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack
et Scheduler Miniport
IPX Enabled: False
Network Adapter 2
RAS Async Adapter
IPX Enabled: False
Network Adapter 3
Packet Scheduler Miniport
IPX Enabled: False
Network Adapter 4
WAN Miniport (L2TP)
IPX Enabled: False
Network Adapter 5
WAN Miniport (PPTP)
IPX Enabled: False
Network Adapter 6
WAN Miniport (PPPOE)
IPX Enabled: False
Network Adapter 7
Direct Parallel
IPX Enabled: False
Network Adapter 8
WAN Miniport (IP)
IPX Enabled: False
Network Adapter 9
Packet Scheduler Miniport
IPX Enabled: False
Top of page
Enumerating the Network Protocols on a ComputerIf you need to determine which network protocols are installed on a specific host, the WMI class
Win32_NetworkProtocol provides access to a variety of parameters for each protocol. For the
purposes of this paper, however, you probably need to know only whether TCP/IP, NetBIOS, and
possibly IPX are installed, even though the class also returns information about other protocols such
as QoS RSVP. Almost all the other properties of this class return details that are not relevant to
scripting network clients.
You can also find out whether TCP/IP or IPX is installed on each network adapter by checking,
respectively, the IPEnabled or IPXEnabled properties of Win32_NetworkAdapterConfiguration. To
obtain information about NetBIOS on specific network adapters, use the TcpipNetbiosOptions
property of Win32_NetworkAdapterConfiguration.
Win32_NetworkProtocol has no methods. All its properties are read-only and apply to the computer
system as a whole, rather than to each network adapter (as most
Win32_NetworkAdapterConfiguration properties do).
The way in which Win32_NetworkProtocol packages settings varies for each protocol. TCP/IP is listed
as two protocol drivers: MSAFD Tcpip [TCP/IP] for TCP; and MSAFD Tcpip [UDP/IP] for UDP. Two
NetBIOS interfaces are listed per network adapter (identified by GUID), one is called SEQPACKET and
the other is called DATAGRAM.
Scripting Steps
Listing 51 lists all the network protocols installed on a computer.
1. Create a variable and assign the name of a computer to it. For the local computer, simply
specify "." as the computer name. To run this script remotely, specify the name of an
accessible remote computer on your network on which you have administrative privileges. The
name can be in the form of either a host name or an IP address.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the ExecQuery method to query the Win32_NetworkProtocol class.
This returns a collection consisting of all the network protocols installed on the computer.
4. For each installed network protocol in the collection, display the protocol name, description and
status.
Listing 51 Netprotocols.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNetProtocols = objWMIService.ExecQuery _
("SELECT * FROM Win32_NetworkProtocol")
WScript.Echo VbCrLf & "Host: " & strComputer & VbCrLf & _
" Network Protocols Installed"
For Each objNetProtocol In colNetProtocols
WScript.Echo VbCrLf & " Protocol Name: " & objNetProtocol.Name
WScript.Echo " Description: " & objNetProtocol.Description
WScript.Echo " Status: " & objNetProtocol.Status
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>netprotocols.vbs
Host: .
Network Protocols Installed
Protocol Name: MSAFD Tcpip [TCP/IP]
Description: TCP/IP Protocol Driver
Status: OK
Protocol Name: MSAFD Tcpip [UDP/IP]
Description: TCP/IP Protocol Driver
Status: OK
Protocol Name: RSVP UDP Service Provider
Description: QoS RSVP
Status: Unknown
Protocol Name: RSVP TCP Service Provider
Description: QoS RSVP
Status: Unknown
Protocol Name: MSAFD NetBIOS [\Device\NetBT_Tcpip_{90505148-4B0A-495D-A68D-A
131E8EFF247}] SEQPACKET 0
Description: NetBIOS Interface
Status: OK
Protocol Name: MSAFD NetBIOS [\Device\NetBT_Tcpip_{90505148-4B0A-495D-A68D-A
131E8EFF247}] DATAGRAM 0
Description: NetBIOS Interface
Status: OK
Protocol Name: MSAFD NetBIOS [\Device\NetBT_Tcpip_{837F1F4E-3E51-4718-95B0-C
5E31D76BCD1}] SEQPACKET 1
Description: NetBIOS Interface
Status: OK
Protocol Name: MSAFD NetBIOS [\Device\NetBT_Tcpip_{837F1F4E-3E51-4718-95B0-C
5E31D76BCD1}] DATAGRAM 1
Description: NetBIOS Interface
Status: OK
Protocol Name: MSAFD NetBIOS [\Device\NetBT_Tcpip_{136E1638-D8FC-4182-8FE7-9
3CFEC053BC7}] SEQPACKET 2
Description: NetBIOS Interface
Status: OK
Protocol Name: MSAFD NetBIOS [\Device\NetBT_Tcpip_{136E1638-D8FC-4182-8FE7-9
3CFEC053BC7}] DATAGRAM 2
Description: NetBIOS Interface
Status: OK
Top of page
Tools for Scripting Other Network ProtocolsThe Windows operating system provides tools and registry keys to use for scripting IPSec and other
network protocols on clients. Table 35 lists the command-line tools for scripting IPSec and other
protocols.
Table 35 Command-Line Tools for IPSec and Other Protocols
Command-Line Tool Where AvailableArp.exe Windows operating systems1
Getmac.exe Windows 2000 Resource Kit
Hostname.exe Windows operating systems
Ipconfig.exe Windows operating systems
Ipseccmd.exe Windows operating systems
Listadapters.vbs Windows 2000 Resource Kit
Command-Line Tool Where AvailableNetconnections.vbs Windows 2000 Resource Kit
Netipconfig.pl Windows 2000 Resource Kit
Netipfilteringconfig.pl Windows 2000 Resource Kit
Netipxspxconfig.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 systems
Protocolbinding.vbs Windows 2000 Resource Kit
Remote.exe Windows Server 2003 Support Tools
Remote Command Service (Rcmd.exe and Rcmdsvc.exe) Windows 2000 Resource Kit
Remote Console Windows 2000 Resource Kit
Rsh.exe and Rshsvc.exe: TCP/IP Remote Shell Service Windows 2000 Resource Kit
Subnet_op.vbs Windows 2000 Resource Kit
Telnet.exe Windows operating systems
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 Tools
1 Windows 2000, Windows XP and Windows Server 2003. May also be present on other versions of Windows.
Table 36 lists the WSH objects to use for scripting other network protocols.
Table 36 WSH Objects for Other Network Protocols
WSH ObjectWshController
WshNetwork
WshShell
Table 37 lists the WMI classes to use for scripting other network protocols.
Table 37 WMI Classes for Other Network Protocols
WMI ClassWin32_NetworkAdapterConfiguration
Win32_NetworkAdapter
Win32_NetworkAdapterSetting (association Win32_NetworkAdapter -
Win32_NetworkAdapterConfiguration)
Win32_NetworkProtocol
Win32_OperatingSystem
Win32_ProtocolBinding (association class)
Table 38 lists the registry keys to use for scripting other network protocols.
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 38 Registry Subkeys Related to Other Network Protocols
Registry SubkeysHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Netman
Automating TCP/IP Networking on ClientsPart 8: Using Advanced Scripting Techniques to Manage Networks
Published: July 12, 2004In addition to the functionality offered by Win32_NetworkAdapterConfiguration and similar classes,
WMI contains other classes that can be useful for managing network clients. This section provides
advanced scripting techniques, including scripting steps and sample scripts, for these tasks:
• Coordinating system time across a network.
Several classes enable you to coordinate system dates and times by using scripts.
• Changing networking settings in the registry.
The Windows registry, including all its settings, is accessible to scripting by using the System
Registry WMI provider.
You can also use these advanced scripting techniques to script other areas of system administration
besides TCP/IP networking.
On This Page
Coordinating System Time Across a Network
Changing Networking Settings in the Registry
Tools for Network Management with Advanced Scripting Techniques
Coordinating System Time Across a NetworkSome operating system features and client/server applications depend on synchronized dates and
time among computers on a network. For example, comparisons of the time stamps of files or
events on different computers produce reliable data only if the computers’ system times match.
Caution
Active Directory automatically synchronizes dates and times for computers that have accounts in
the directory service. Do not change the date and time of a computer that is joined to an Active
Directory domain.
Rather than concentrating date and time functionality in one or two classes, WMI distributes it
among several classes, some of which are more general containers:
• Win32_ComputerSystem and Win32_OperatingSystem both include, among many others, properties
and methods that can manage date and time settings.
• Win32_TimeZone, Win32_CurrentTime, Win32_LocalTime, and Win32_UTCTime (the latter three are
new for Windows XP) also contain read-only properties that expose each component of the date and
time, time zone, and daylight time setting.
• The WMI Scripting Library SwbemDateTime object, which is new in Windows XP, can also be used to
manipulate date and time objects together with the other classes.
Win32_OperatingSystemTable 39 describes the read-only properties that the Win32_OperatingSystem class provides for
managing date and time settings.
Table 39 Win32_OperatingSystem Date & Time Properties
Property Type DescriptionCurrentTimeZone
(read-only)
sint16 Number of minutes that an operating system is offset
from Greenwich Mean Time (GMT). The number can be
positive, negative, or zero.
LocalDateTime
(read-only)
datetime Operating system's version of the local date and time of
day.
Table 40 describes the Win32_OperatingSystem method for managing date and time settings.
Table 40 Win32_OperatingSystem Date & Time Method
Method Parameters DescriptionSetDateTime LocalDateTime – datetime
Value of the current time.
Sets the current system time on the computer. The
calling process must have the SE_SYSTEMTIME_NAME
privilege.
This method returns a positive integer:
• 0 indicates successful completion.
• Numbers greater than 0 indicate an error.
Win32_ComputerSystemTable 41 describes the Win32_ComputerSystem properties, two of which are read/write, for
managing date and time settings.
Table 41 Win32_ComputerSystem Date & Time Properties
Property Type DescriptionCurrentTimeZone
(read/write)
sint16
Unit: Minutes
Amount of time the unitary computer system is offset
from Coordinated Universal Time (UTC).
DaylightInEffect
(read-only)
Boolean Daylight savings mode is ON.
EnableDaylightSavingsTime
(read/write)
In Windows XP and Windows
Server 2003 only
Boolean Enables daylight saving time (DST) on a computer. A
value of true indicates that the system time changes to
an hour ahead or behind when DST starts or ends. A
value of false indicates that the system time does not
change to an hour ahead or behind when DST starts or
ends. A value of NULL indicates that the DST status is
unknown on a system.
Win32_TimeZoneWin32_TimeZone represents the time zone information for a Windows system, which includes
changes needed for the daylight saving time transition. This class includes several properties, all
read-only, but no methods. The properties include components of the date and time for standard
and daylight time and the bias between them.
Win32_CurrentTimeUse Win32_LocalTime or Win32_UTCTime rather than this class.
New for Windows XP and Windows Server 2003
An abstract singleton class, which does not have instances, Win32_CurrentTime serves as a
template for the other time classes. It describes a point in time by using the component items such
as seconds, minutes, hours, days, days of the week, week in the month, months, quarters, and
years. Note that although the SDK shows a Milliseconds property for this class, it is not actually
implemented.
Win32_LocalTime and Win32_UTCTime both inherit from Win32_CurrentTime.
Win32_LocalTimeNew for Windows XP and Windows Server 2003
The Win32_LocalTime class represents the local time on the computer. It inherits from
Win32_CurrentTime and exposes the same properties. The Hour property returns the local time on a
24-hour clock. Note that although the SDK shows a Milliseconds property for this class, it is not
actually implemented.
Win32_UTCTimeNew for Windows XP and Windows Server 2003
The Win32_UTCTime class represents the local time on the computer. It inherits from
Win32_CurrentTime and exposes the same properties. The Hour property returns Coordinated
Universal Time (UTC) on a 24–hour clock. Note that although the SDK shows a Milliseconds property
for this class, it is not actually implemented.
WMI Scripting Library SwbemDateTime ObjectNew for Windows XP and Windows Server 2003
This helper object parses and converts WMI datetime values (for example, the LocalDateTime
property of Win32_OperatingSystem) to and from other formats. For more information, see
“SWbemDateTime” in the WMI SDK at http://go.microsoft.com/fwlink/?LinkId=29997.
VBScript Now FunctionThis function extracts the current system date and time from the computer running the script.
Retrieving the Current Time by Using the VBScript Now FunctionThis script retrieves the current system time on a computer by using the VBScript Now function.
Listing 52 Time-get.vbs
1WScript.Echo "Current Date and Time: " & Now
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>time-get.vbs
Current Date and Time: 5/19/2004 2:46:29 PM
Retrieving the Local Time by Using WMIWMI provides a less simple but more flexible way than the VBScript Now function to read the local
date and time. The Win32_LocalTime class exposes properties representing the year, quarter,
month, week in month, date, day of week, hour (based on a 24-hour clock), minute, and second of
local system time.
Scripting Steps
Listing 53 retrieves the local time on a computer with the WMI Win32_LocalTime class. This class is
new for Windows XP, so the script runs only against Windows XP and Windows Server 2003.
1. Create a variable and assign the name of a computer to it. For the local computer, simply
specify "." as the computer name. To run this script remotely, specify the name of an
accessible remote computer on your network on which you have administrative privileges. The
name can be in the form of either a host name or an IP address.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the ExecQuery method to query the Win32_LocalTime class.
This returns a collection consisting of one object representing the local time on the computer.
4. Use the properties of the local time object to display the month, day, year, quarter, week in the
month, day of the week and time.
Listing 53 Time-get-local.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colLocalTimes = objWMIService.ExecQuery("Select * from Win32_LocalTime")
For Each objLocalTime in colLocalTimes
Wscript.Echo "Date: " & objLocalTime.Month & "/" & objLocalTime.Day & _
"/" & objLocalTime.Year
Wscript.Echo "Quarter: " & objLocalTime.Quarter
Wscript.Echo "Week In the Month: " & objLocalTime.WeekInMonth
Wscript.Echo "Day Of the Week: " & objLocalTime.DayOfWeek
Wscript.Echo "Time: " & objLocalTime.Hour & ":" & objLocalTime.Minute & _
":" & objLocalTime.Second
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>time-get-local.vbs
Date: 5/19/2004
Quarter: 2
Week In the Month: 4
Day Of the Week: 3
Time: 16:55:39
Retrieving the UTC Time by Using WMIThe Greenwich Observatory in the United Kingdom keeps Coordinated Universal Time (UTC), which
is the international standard time. UTC differs from local time by a differential for each local time
zone, which is exposed by other classes discussed later in this section. In comparing system times
of computers in different time zones, UTC can be useful because it is the current time at the
Greenwich Observatory and thus has the same value anywhere in the world.
Scripting Steps
Listing 54 retrieves current UTC on a computer by using the WMI Win32_UTCTime class. Like
Win32_LocalTime, in Win32_UTCTime the hour uses a 24-hour clock. This class is new for
Windows XP, so the script runs only against Windows XP and Windows Server 2003.
1. Create a variable to specify the computer name.
2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
3. Use the ExecQuery method to query the Win32_UTCTime class.
This returns a collection consisting of one object representing the UTC according to this
computer.
4. Use the properties of the UTC object to display the month, day, year, quarter, week in the
month, day of the week and time.
Listing 54 Time-get-utc.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colUTCTimes = objWMIService.ExecQuery("Select * from Win32_UTCTime")
For Each objUTCTime in colUTCTimes
Wscript.Echo "Date: " & objUTCTime.Month & "/" & objUTCTime.Day & _
"/" & objUTCTime.Year
Wscript.Echo "Quarter: " & objUTCTime.Quarter
Wscript.Echo "Week In the Month: " & objUTCTime.WeekInMonth
Wscript.Echo "Day Of the Week: " & objUTCTime.DayOfWeek
Wscript.Echo "Time: " & objUTCTime.Hour & ":" & objUTCTime.Minute & _
":" & objUTCTime.Second
Next
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>time-get-utc.vbs
Date: 5/19/2004
Quarter: 2
Week In the Month: 4
Day Of the Week: 3
Time: 23:56:29
Retrieving the Time from a Remote ComputerAs with other WMI classes, to get UTC or local time from a remote computer, simply change the
name of the computer in strComputer (see line 3 of the script) to a remote computer on which you
have administrative credentials and WMI handles the details for you.
Comparing Local Times on Two ComputersOne way to compare system dates and times on two computers in the same time zone is provided
by the LocalDateTime property of the Win32_OperatingSystem class. This read-only property returns
the operating system’s setting for the local date and time, including the offset from Greenwich Mean
Time, indicating the time zone. This approach works on networks that contain computers that run
operating systems older than Windows XP and Windows Server 2003.
To compare dates and times on computers in different time zones, you can adapt this script to
compensate for time zones by calculating and applying the difference between the last four digits of
the datetime value returned by LocalDateTime. These digits begin with a positive or negative sign
and a three-digit offset indicating the number of minutes that the local time zone deviates from
UTC.
Optionally, you can compare the dates and times returned by Win32_UTCTime. These dates and
times are the same on two synchronized computers regardless of local time zone. However, this
class is new to Windows XP and Windows Server 2003.
Scripting Steps
Listing 55 compares dates and times on two computers, either a local and a remote computer or
two remote computers.
1. Create variables to specify the names of the two computers.
2. On each of the two computers, use a GetObject call to connect to the WMI namespace root\
cimv2, and set the impersonation level to “impersonate.”
3. On each computer, use the ExecQuery method to query the Win32_OperatingSystem class.
This returns two collections of operating system objects, with one object in each collection.
4. After each of the ExecQuery calls returns, call the VBScript Now function and assign the
seconds from each time to a variable.
The Now function returns the system date and time at the moment it is run.
5. If the difference between the two time variables is not 0, assign it to a variable. This
represents the difference between the times that the two Win32_OperatingSystem queries
finished executing.
The time retrieved by the LocalDateTime property on each computer depends on the exact
moment when the query executes.
6. Loop through each operating system object in the collection on the first computer with For
Each.
7. Within the first For Each loop, loop through each operating system object in the collection on
the second computer with a nested For Each loop.
8. Use the LocalDateTime property to retrieve the local system time from the two computers.
9. Truncate the datetime objects returned by LocalDateTime to the date, hour and minute
values and, if there is any differential between the two Now values, use it to adjust the first
time before comparing the two times.
10. Call the WMIDateToString function to display the two adjusted system dates and times in
more readable format.
For more information about WMIDateToString, see “Displaying DHCP Client Information”
earlier in this paper.
11. Compare the two adjusted dates and times and output the results of the comparison.
Note
The dates and times retrieved by those two collections are static after ExecQuery() runs. That
is, they are a snapshot of the date and time at the moment the query ran. If the network
connection is good and both computers are not busy, less than a second may separate the
two queries, and it will not be necessary to compensate for latency. If more than a second has
elapsed from the first Now function call to the second, the script compensates for the latency
by adding the difference to the time retrieved from the first computer (line 28).
Listing 55 Time-compare.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
On Error Resume Next
strComputer1 = "."
strComputer2 = "server-d1"
Set objWMIService1 = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer1 & "\root\cimv2")
Set objWMIService2 = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer2 & "\root\cimv2")
Set colOSes1 = objWMIService1.ExecQuery("Select * from " & _
"Win32_OperatingSystem")
strTime1 = Now
Set colOSes2 = objWMIService2.ExecQuery("Select * from " & _
"Win32_OperatingSystem")
strTime2 = Now
intSeconds1 = CInt(Left(Right(strTime1, 5), 2))
intSeconds2 = CInt(Left(Right(strTime2, 5), 2))
intDiff = 0
If intSeconds1 <> intSeconds2 Then
intDiff = intSeconds2 - intSeconds1
End If
For Each objOS1 in colOSes1
For Each objOS2 in colOSes2
intDateTime1 = Left(objOS1.LocalDateTime, 14)
intDateTime2 = Left(objOS2.LocalDateTime, 14)
If intDiff <> 0 Then
intDateTime1 = intDateTime1 + intDiff
End If
WScript.Echo "Adjusted time on " & strComputer1 & ": " & _
WMIDateToString(intDateTime1)
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>time-compare.vbs
Adjusted time on .: 5/19/2004 5:01:26 PM
Adjusted time on server1: 5/19/2004 5:05:52 PM
Dates and times are not equal.
Setting the Time on One Computer by Using Command-Line ToolsTwo command-line tools, Date.exe and Time.exe, allow you to set the local system date and time on
a local computer:
• Date.exe uses the following format:
date date/month/year
For example, the following command line sets the system date to March 8, 2004:
date 03/08/2004
When you run this command without arguments, it retrieves the current system date.
• Time.exe uses the following format where hours:minutes is in 24-hour clock format:
time hours:minutes
For example, the following command line sets the system time to 6:25 p.m:
time 18:25
When you run this command without arguments, it retrieves the current system date.
Date.exe and Time.exe are available in all Windows operating systems.
The net time command provides options that enable you to synchronize time with a time server.
Setting the Time on One Computer by Using WMIUsing WMI, you can read and set times on remote as well as local computers. The WMI class
Win32_OperatingSystem includes a read-only property, LocalDateTime, which returns the operating
system’s setting for the local date and time, including the offset from Greenwich Mean Time
indicating the time zone.
Caution
Active Directory automatically synchronizes dates and times for computers that have accounts in
the directory service. Do not change the date and time of a computer that is joined to an Active
Directory domain.
Win32_OperatingSystem also includes a method, SetDateTime(), which takes a date and time in the
form of a DATETIME object as a parameter, and sets this as the computer's current date and time.
SetDateTime() returns zero (0) to indicate success and any other number to indicate an error. To
call SetDateTime(), the script must be running under credentials that have the
SE_SYSTEMTIME_NAME privilege.
The following script uses the LocalDateTime property and the SetDateTime() method to set a new
date and time for a local or remote computer.
The new date and time must be in DATETIME format, a WMI data type that is a fixed-length string
representing a specific date and time in WMI. The string takes the form:
yyyymmddHHMMSS.mmmmmmsUUU
Table 42 describes the valid values for the DATETIME fields. All fields must match the field length
indicated in the table; use leading zeros if needed.
Table 42 DATETIME Field Descriptions
Field Descriptionyyyy Four-digit year (0000–9999).
mm Two-digit month (01–12).
dd Two-digit day of the month (01–31). This value must be appropriate for the month. For
example, February 31 is invalid. However, your implementation does not have to check
for valid data.
HH Two-digit hour of the day using the 24-hour clock (00–23).
MM Two-digit minute in the hour (00–59).
SS Two-digit number of seconds in the minute (00–59).
mmmmmm Six-digit number of microseconds in the second (000000–999999).
s Plus sign (+) or minus sign (–) to indicate a positive or negative offset from UTC.
UUU Three-digit offset indicating the number of minutes that the originating time zone
deviates from UTC. For WMI, it is encouraged, but not required, that you convert times
to GMT (a UTC offset of zero).
You can use asterisks to indicate unused fields or as a wildcard value. For example, a date and time
with an unspecified year can occur in any year, as in the following example:
****0416******.******+***
If you want to leave a field unspecified, you must replace the entire field with asterisks. The
following examples illustrate valid and invalid uses of asterisks:
19980416******.000000+*** ' Valid
1998-04-16 ******:*** ' Invalid
199*0416******.000000+*** ' Invalid
199*-04-16 ******:*** ' Invalid
For more information about the DATETIME data type, see the WMI SDK topic "Date and Time
Format," from which this explanation is adapted. For more information about how to work with dates
and times in scripting, see the Windows 2000 Scripting Guide topics "Working with Dates and
Times" in the "VBScript Primer" and "WMI Scripting Primer" chapters at
http://go.microsoft.com/fwlink/?LinkId=30137 and http://go.microsoft.com/fwlink/?LinkId=30136.
Scripting Steps
Listing 56 sets the system time on a local or remote computer. This script illustrates how to use the
SetDateTime method of Win32_OperatingSystem. However, the precision of this approach is
typically limited to the minute, rather than the second, because it requires entering the correct time
at the last moment.
1. Create a variable and assign the name of a computer to it.
2. Create a variable and assign a string (use WMI DATETIME format) representing the date and
time you want to set. Just before running the script, replace the WMI DATETIME format with the
actual time you want to set. The sample date in the script is equivalent to May 7, 2004, 5:01
p.m. with a negative offset of 8 hours (480 minutes) from GMT.
3. Use a GetObject() call to connect to the WMI namespace root\cimv2, and set the impersonation
level to “impersonate.”
4. Call the ExecQuery method to query the Win32_OperatingSystem class.
This returns a collection consisting of one object representing the operating system.
5. For each operating system object in the collection, perform the following tasks.
6. Call the SetDateTime method of Win32_OperatingSystem, passing it the datetime value.
7. Check the return value of the method and display a success or error method.
8. Requery Win32_OperatingSystem and get the refreshed LocalDateTime property reflecting the
change.
9. Call the WMIDateToString function to display the datetime value in more readable format. For
more information about this function, see "Displaying DHCP Client Information" earlier in this
paper.
Listing 56 Time-set.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
On Error Resume Next
strComputer = "."
dtmNewDateTime = "20040520151300.000000-480"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate, " _
& "(Systemtime)}!\\" & strComputer & "\root\cimv2")
Set colOSes = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem")
For Each objOS In colOSes
intSet = objOS.SetDateTime(dtmNewDateTime)
If intSet = 0 Then
Wscript.Echo "Successfully set new date and time."
Else
Wscript.Echo "Unable to set mew date and time."
End If
Next
Set colOSes = objWMIService.ExecQuery("SELECT * FROM Win32_OperatingSystem")
For Each objOS In colOSes
Wscript.Echo "New date and time: " & WMIDateToString(objOS.LocalDateTime)
Next
'******************************************************************************
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))
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>time-set.vbs
Successfully set new date and time.
New date and time: 5/20/2004 3:08:49 PM
Synchronizing Times on Two ComputersRunning a network often requires that system times be synchronized across it. Some applications,
such as those that compare files based on time stamps, require that times on different hosts agree
closely.
More sophisticated methods of ensuring accurate and synchronized time across a network use tools
that synchronize with public time servers. This section, however, shows how to use a simple script
to compare times on two computers, and if they are not identical, to set the time on the target
computer to agree with the reference computer. This approach assumes that you have already
accessed an external source and manually set the correct time on the reference computer.
A more complex script might automate obtaining a reference time from an external source and then
setting the target computers to it. Although WMI does not provide this functionality, you might be
able to do it with a command-line tool or a Web application that is run through the WSH Exec
method.
Caution
Active Directory automatically synchronizes dates and times for computers that have accounts in
the directory service. Do not change the date and time of a computer that is joined to an Active
Directory domain.
The net time command provides options that enable you to synchronize time by using a time
server.
Scripting Steps
Listing 57 compares system time (compensated for time zone) on two computers, by using the
LocalDateTime property of the Win32_OperatingSystem class. For each computer, the script takes
the leftmost fourteen characters of LocalDateTime (the ones that indicate date and time down to
the second) and compares the truncated string.
If the time on the first computer does not agree with the second, the script uses the SetDateTime()
method of Win32_OperatingSystem to set the second computer to the time on the first. This takes
into account daylight saving differences, because if the two computers are in the same time zone
and the time is the same, the computers’ daylight saving time setting must also be the same.
When you use this script, the degree of precision for time synchronization is typically limited to the
minute, rather than the second, because of network latency and the time necessary to execute
code.
To carry out this task, the script must:
1. Create variables to specify the names of the two computers.
2. On each of the two computers, use a GetObject call to connect to the WMI namespace root\
cimv2, and set the impersonation level to “impersonate.”
Note that this script does not check for network connectivity to either computer.
3. On each computer, use the ExecQuery method to query the Win32_OperatingSystem class.
This returns two collections of operating system objects, with one object in each collection.
4. After each of the ExecQuery calls returns, call the VBScript Now function and assign the
seconds from each time to a variable.
The Now function returns the system date and time at the moment it is run.
5. Assign the difference between the two time variables to another variable, which represents
the difference between the times that the two Win32_OperatingSystem queries were
executed. The moment when each query runs determines the time that the LocalDateTime
property retrieves for that computer.
6. If the difference between the two time variables is not 0, assign it to a variable, which
represents the difference between the times the two Win32_OperatingSystem queries finished
executing.
The time retrieved by the LocalDateTime property on each computer depends on the exact
moment when the query executes.
7. Loop through each operating system object in the collection on the first computer with For
Each.
8. Within the first For Each loop, loop through each operating system object in the collection on
the second computer with a nested For Each loop.
9. Use the LocalDateTime property to retrieve the local system time from the two computers.
10. Assign the LocalDateTime property from the first (reference) computer to a variable that will
be used to set the time on the second (target) computer if necessary.
11. Truncate the datetime objects returned by LocalDateTime to the date, hour and minute
values.
12. If there is any differential between the two Now values, use it to adjust the reference time
before comparing the two times.
13. Compare the two adjusted dates and times.
14. If the dates and times are equal, display a message.
15. If the dates and times are not equal, call the SetDateTime method of Win32_OperatingSystem
on the target computer.
16. Check the return value of the method and display a success or error message.
Listing 57 Time-sync.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
On Error Resume Next
strComputer1 = "."
strComputer2 = "client1"
Set objWMIService1 = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer1 & "\root\cimv2")
Set objWMIService2 = GetObject("winmgmts:{impersonationLevel=impersonate, " _
& "(Systemtime)}!\\" & strComputer2 & "\root\cimv2")
Set colOSes1 = objWMIService1.ExecQuery("SELECT * FROM Win32_OperatingSystem")
strTime1 = Now
Set colOSes2 = objWMIService2.ExecQuery("SELECT * FROM Win32_OperatingSystem")
strTime2 = Now
intSeconds1 = CInt(Left(Right(strTime1, 5), 2))
intSeconds2 = CInt(Left(Right(strTime2, 5), 2))
intDiff = 0
If intSeconds1 <> intSeconds2 Then
intDiff = intSeconds2 - intSeconds1
End If
For Each objOS1 in colOSes1
For Each objOS2 in colOSes2
dtmRefDateTime = objOS1.LocalDateTime
intDateTime1 = Left(dtmRefDateTime, 14)
intDateTime2 = Left(objOS2.LocalDateTime, 14)
If intDiff <> 0 Then
intDateTime1 = intDateTime1 + intDiff
End If
If intDateTime1 = intDateTime2 Then
Wscript.Echo "Dates and times on " & strComputer1 & " and " & _
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>time-sync.vbs
Successfully synchronized date and time on client1 with reference (.).
Synchronizing Times on Multiple ComputersExtending the time comparison from two to any number of computers is relatively simple. The
following script uses the same basic code as Time-sync.vbs. However, it gets a list of computers
from an array and then iterates through each, comparing the system time to that of the reference
computer, and if necessary, synchronizing them.
This script uses a rough algorithm for time comparison and synchronization, illustrating one way to
synchronize computer times by using scripting. However, if network latency is too great, system
times on computers synchronized with this approach may vary unacceptably from the reference
time.
Caution
Active Directory automatically synchronizes dates and times for computers that have accounts in
the directory service. Do not change the date and time of a computer that is joined to an Active
Directory domain.
Scripting Steps
Listing 58 compares system time (compensated for time zone) on multiple computers, the names or
IP addresses of which are retrieved from an array. If the time on any computer does not agree with
the standard time, the script resets it.
1. Create a variable to specify the name of the reference computer.
2. Create an array to contain the names or IP addresses of the target computers.
3. On the reference computer, use a GetObject call to connect to the WMI namespace root\
cimv2, and set the impersonation level to “impersonate.”
4. Loop through the array of target computers, performing the following tasks on each.
5. Use the Exec method of the WshShell object to ping the target computer in order to verify
connectivity.
6. On each computer, use the ExecQuery method to query the Win32_OperatingSystem class.
This returns two collections of operating system objects, with one object in each collection.
7. After each of the ExecQuery calls returns, call the VBScript Now function and assign the
seconds from each time to a variable.
The Now function returns the system date and time at the moment it is run.
8. Assign the difference between the two time variables to another variable, which represents
the difference between the times the two Win32_OperatingSystem queries were executed.
The moment at which each query runs determines the time that will be retrieved by the
LocalDateTime property on that computer.
9. If the difference between the two time variables is not 0, assign it to a variable. This variable
represents the difference between the times the two queries of Win32_OperatingSystem
finished executing.
The time retrieved by the LocalDateTime property on each computer depends on the exact
moment when the query executes.
10. Loop through each operating system object in the collection on the first computer with For
Each.
11. Within the first For Each loop, loop through each operating system object in the collection on
the second computer with a nested For Each loop.
12. Use the LocalDateTime property to retrieve the local system time from the two computers.
13. Assign the LocalDateTime property from the first (reference) computer to a variable that will
be used to set the time on the second (target) computer if necessary.
14. Truncate the datetime objects returned by LocalDateTime to the date, hour and minute
values.
15. If there is any differential between the two Now values, use it to adjust the reference time
before comparing the two times.
16. Compare the two adjusted dates and times.
17. If the dates and times are equal, display a message.
18. If the dates and times are not equal, call the SetDateTime method of Win32_OperatingSystem
on the target computer.
19. Check the return value of the method and display a success or error message.
Listing 58 Time-sync-multi.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
On Error Resume Next
strReference = "."
arrTargets = Array("client1", "client2", "192.168.0.1", "192.168.0.2")
Set objWMIService1 = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strReference & "\root\cimv2")
For Each strTarget In arrTargets
WScript.Echo VbCrLf & String(80, "-") & VbCrLf & "Target: " & strTarget _
& VbCrLf
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "reply from") Then
Set objWMIService2 = GetObject("winmgmts:{impersonationLevel=" _
& "impersonate, (Systemtime)}!\\" & strTarget & "\root\cimv2")
Set colOSes1 = objWMIService1.ExecQuery("SELECT * FROM " & _
"Win32_OperatingSystem")
strTime1 = Now
Set colOSes2 = objWMIService2.ExecQuery("SELECT * FROM " & _
"Win32_OperatingSystem")
strTime2 = Now
intSeconds1 = CInt(Left(Right(strTime1, 5), 2))
intSeconds2 = CInt(Left(Right(strTime2, 5), 2))
intDiff = 0
If intSeconds1 <> intSeconds2 Then
intDiff = intSeconds2 - intSeconds1
End If
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>time-sync-multi.vbs
--------------------------------------------------------------------------------
Target: client1
Successfully synchronized date and time on client1 with reference (.).
--------------------------------------------------------------------------------
Target: client2
Successfully synchronized date and time on client2 with reference (.).
--------------------------------------------------------------------------------
Target: 192.168.0.1
192.168.0.1 did not respond to ping.
--------------------------------------------------------------------------------
Target: 192.168.0.2
192.168.0.2 did not respond to ping.
Top of page
Changing Networking Settings in the RegistryYou can retrieve and change TCP/IP networking settings by using the registry. The registry contains
some networking settings that are not accessible through WMI classes, command-line tools, or the
Windows interface.
To work with the registry, use the StdRegProv class of the System Registry WMI provider. This class
is located in the \root\default namespace; whereas all the Win32_ classes that were discussed so far
in this paper are located in the \root\cimv2 namespace.
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.
To use this class, change the lines of the script that connect to WMI to:
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
In the GetObject call that binds (creates a reference) to the WMI service, specify the \root\default
namespace as part of the object path (rather than the \root\cimv2 namespace). Then create an
instance of the class directly by appending a colon and the name of the StdRegProv class to the end
of the object path.
The StdRegProv class returns a reference to a single instance in the form of an SWbemObject,
representing the whole registry (of which there is only one per operating system). This is different
from the collection of (often) multiple instances in the form of an SWbemObjectSet returned by
Win32_NetworkAdapterConfiguration and most other classes used so far. Because this is an
SWbemObject rather than an SWbemObjectSet, you do not have to call ExecQuery and work with a
collection of instances. Rather, you can use dot notation to call methods of the StdRegProv class
directly on the reference, for example:
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strEntryName,strValue
If you are unfamiliar with SWbemObject and SwbemObjectSet objects, which are part of the WMI
scripting library object model, see these references:
• The "WMI Scripting Library" topic in the "WMI Scripting Primer" section of the Windows 2000
Scripting Guide at http://go.microsoft.com/fwlink/?LinkId=29996.
• The "Scripting API for WMI" topic in the WMI Reference of the WMI SDK at
http://go.microsoft.com/fwlink/?LinkId=29998.
The StdRegProv class does not expose any properties. Table 43 describes the StdRegProv methods.
Table 43 StdRegProv Methods
Method DescriptionCheckAccess Verifies that the user has the specified access permissions.
CreateKey Creates a subkey.
DeleteKey Deletes a subkey.
DeleteValue Deletes a named value.
EnumKey Enumerates subkeys.
EnumValues Enumerates the named values of a key.
GetBinaryValue Gets the binary data value of a named value.
GetDWORDValue Gets the DWORD data value of a named value.
GetExpandedStringValue Gets the expanded string data value of a named value.
GetMultiStringValue Gets the multiple string data values of a named value.
GetStringValue Gets the string data value of a named value.
SetBinaryValue Sets the binary data value of a named value.
SetDWORDValue Sets the DWORD data value of a named value.
SetExpandedStringValue Sets the expanded string data value of a named value.
SetMultiStringValue Sets the multiple string values of a named value.
SetStringValue Sets the string value of a named value.
All the methods in the previous table return a positive integer:
• 0 indicates successful completion.
• Numbers greater than 0 indicate that an error occurred.
For more information about the StdRegProv class and its methods, see "StdRegProv" in the WMI SDK
at http://go.microsoft.com/fwlink/?LinkId=29999.
The GetStringValue and GetDWORDValue methods return information to the script through an out
parameter, a mechanism not previously mentioned in this paper. In the GetStringValue method, the
script passes in the first three parameters to tell the method from which entry to fetch the value.
The information is returned in the final parameter — in this case in the form of the string variable
strValue. After the line executes, this variable now contains the value of the registry entry
Hostname in the location HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\
Parameters. The final line of the script displays this value.
The scripts in this section get and set both string (REG_SZ) and DWORD (REG_DWORD, a 32-bit
integer type) values from the registry. Different methods are used to retrieve and set string and
DWORD types. The StdRegProv class also includes other methods for multi-string, expanded string,
and binary values.
The entry whose value is a string (Hostname) is:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Hostname
The entry whose value is a DWORD (DeadGWDetectDefault) is:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\
DeadGWDetectDefault
Table 44 describes the registry subkeys that are related to TCP/IP client networking.
Table 44 Registry Subkeys Related to TCP/IP Client Networking
Registry Subkey DescriptionHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet
\Services\Tcpip\Parameters
Contains global TCP/IP configuration settings that
apply to all network adapters on the computer.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet
\Services\Tcpip\Parameters\Interfaces
Contains TCP/IP configuration settings for each
specific adapter (interface) in its subkeys, which
are identified by GUID.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet
\Services\Dhcp\Parameters\Options
Contains configuration settings for DHCP options
in its subkeys.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet
\Services\Dnscache\Parameters
Contains configuration settings for local DNS
caching resolver service of the DNS client.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet
\Services\NetBT\Parameters
Contains global configuration settings for
NetBIOS over TCP/IP and WINS that apply to all
network adapters on the computer.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet
\Services\NetBT\Parameters\Interfaces
Contains configuration settings for NetBIOS over
TCP/IP and WINS for each specific adapter
(interface) in its subkeys, which are identified by
GUID.
For more information about using scripting to configure the registry, including detailed information
about many registry entries, see these references:
• The "Registry" section of the Windows 2000 Scripting Guide at
http://go.microsoft.com/fwlink/?LinkId=30001.
• The “Resource Kit Registry Reference for Windows Server 2003” at http://go.microsoft.com/fwlink/?
LinkId=30003 and the Windows 2000 Server “Technical Reference to the Registry” at
http://go.microsoft.com/fwlink/?LinkId=31141.
Getting a String Value from the Registry by Using WMIThis script shows how to retrieve a TCP/IP networking setting (Hostname) from a registry entry
whose value is a string (REG_SZ). The script uses the GetStringValue method of the StdRegProv
class of the System Registry WMI provider.
Scripting Steps
1. Create a constant to contain the hexadecimal value for HKEY_LOCAL_MACHINE.
2. Create a variable and assign the computer name to it. The name can be in the form of either a
host name or an IP address.
3. Create variables for the registry key path and entry name.
4. Use a GetObject call to connect to the WMI namespace root\default on the specified computer;
set the impersonation level to “impersonate"; instantiate the StdRegProv class and assign it to
the variable objReg.
5. Invoke the GetStringValue method of the StdRegProv class, passing it parameters for the
subtree, key path and entry name, and assigning the out parameter for the string value to
strValue.
6. Display the entry name and its string value.
Listing 59 Reg-get-string.vbs
1
2
3
4
5
6
7
8
9
10
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
strKeyPath = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
strEntryName = "Hostname"
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strEntryName,strValue
Wscript.Echo strEntryName & ": " & strValue
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>reg-get-string.vbs
Hostname: client1
Getting a Numeric Value from the Registry by Using WMIThis script shows how to retrieve a TCP/IP networking setting (DeadGWDetectDefault) from a
registry entry whose value is a DWORD (REG_DWORD, a 32-bit integer type). The script uses the
GetDWORDValue method of the StdRegProv class of the System Registry WMI provider.
Scripting Steps
1. Create a constant to contain the hexadecimal value for HKEY_LOCAL_MACHINE.
2. Create a variable and assign the computer name to it. The name can be in the form of either a
host name or an IP address.
3. Create variables for the registry key path and entry name.
4. Use a GetObject call to connect to the WMI namespace root\default on the specified computer;
set the impersonation level to “impersonate"; instantiate the StdRegProv class and assign it to
the variable objReg.
5. Invoke the GetDWORDValue method of the StdRegProv class, passing it parameters for the
subtree, key path and entry name, and assigning the outparameter for the DWORD value to
dwValue.
6. Display the entry name and its DWORD value.
Listing 60 Reg-get-dword.vbs
1
2
3
4
5
6
7
8
9
10
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
strKeyPath = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
strEntryName = "DeadGWDetectDefault"
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strEntryName,dwValue
Wscript.Echo strEntryName & ": " & dwValue
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>reg-get-dword.vbs
DeadGWDetectDefault: 1
Setting a String Value in the Registry by Using WMIThis script shows how to set a TCP/IP networking setting (Hostname) in a registry entry whose value
is a string (REG_SZ). The script uses the SetStringValue method of the StdRegProv class of the
System Registry WMI provider.
Scripting Steps
1. Create a constant to contain the hexadecimal value for HKEY_LOCAL_MACHINE.
2. Create a variable and assign the computer name to it. The name can be in the form of either a
host name or an IP address.
3. Create variables for the registry key path and entry name.
4. Use a GetObject call to connect to the WMI namespace root\default on the specified computer;
set the impersonation level to “impersonate"; instantiate the StdRegProv class and assign it to
the variable objReg.
5. Invoke the SetStringValue method of the StdRegProv class, passing it parameters for the
subtree, key path, entry name, and string value.
6. Invoke the GetStringValue method of the StdRegProv class, passing it parameters for the
subtree, key path and entry name, and assigning the outparameter for the string value to
strValue.
7. Display the entry name and its string value.
Listing 61 Reg-set-string.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
strKeyPath = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
strEntryName = "Domain"
strValue = "fabrikam.com"
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
objReg.SetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strEntryName, strValue
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strEntryName,strValue
Wscript.Echo strEntryName & ": " & strValue
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>reg-set-string.vbs
Domain: fabrikam.com
Setting a Numeric Value in the Registry by Using WMIThis script shows how to set a TCP/IP networking setting (DeadGWDetectDefault) in a registry entry
whose value is a DWORD (REG_DWORD, a 32-bit integer type). The script uses the SetDWORDValue
method of the StdRegProv class of the System Registry WMI provider.
Scripting Steps
1. Create a constant to contain the hexadecimal value for HKEY_LOCAL_MACHINE.
2. Create a variable and assign the computer name to it. The name can be in the form of either a
host name or an IP address.
3. Create variables for the registry key path and entry name.
4. Use a GetObject call to connect to the WMI namespace root\default on the specified computer;
set the impersonation level to “impersonate"; instantiate the StdRegProv class and assign it to
the variable objReg.
5. Invoke the SetDWORDValue method of the StdRegProv class, passing it parameters for the
subtree, key path, entry name, and DWORD value.
6. Invoke the GetDWORDValue method of the StdRegProv class, passing it parameters for the
subtree, key path, and entry name, and assigning the outparameter for the DWORD value to
dwValue.
7. Display the entry name and its DWORD value.
Listing 62 Reg-set-dword.vbs
1
2
3
4
5
6
7
8
9
10
11
12
13
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
strKeyPath = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
strEntryName = "DeadGWDetectDefault"
dwValue = 1
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
objReg.SetDWORDValue HKEY_LOCAL_MACHINE, strKeyPath, strEntryName, dwValue
objReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strEntryName,dwValue
Wscript.Echo strEntryName & ": " & dwValue
When you use Cscript.exe to run this script, output similar to the following is displayed in the
command window:
C:\scripts>reg-set-dword.vbs
DeadGWDetectDefault: 1
Top of page
Tools for Network Management with Advanced Scripting TechniquesThe Windows operating system provides tools and registry keys to use for performing advanced
scripting techniques. Table 45 lists the command-line tools to use for managing your network when
you use advanced scripting techniques.
Table 45 Tools for Advanced Network Management Techniques
Technology Tool Where AvailableCommand-line
tools
Ping.exe Windows operating systems1
Command-line
tools
Remote.exe Windows Server 2003 Support Tools
Command-line
tools
Remote Command Service
(Rcmd.exe and Rcmdsvc.exe)
Windows 2000 Resource Kit
Command-line
tools
Remote Console Windows 2000 Resource Kit
Command-line
tools
Rsh.exe and Rshsvc.exe:
TCP/IP Remote Shell Service
Windows 2000 Resource Kit
Command-line
tools
Telnet.exe Windows operating systems
Command-line Timezone.exe: Windows 2000 Resource Kit
Technology Tool Where Availabletools Daylight Saving Time Update Utility
Command-line
tools
Tzedit.exe: Time Zone Editor Windows 2000 Resource Kit (GUI tool)
Command-line
tools
Wsremote.exe Windows XP Support Tools
WSH WshController
WMI StdRegProv
WMI SwbemDateTime Windows XP and Windows Server 2003
only
WMI Win32_ComputerSystem
WMI Win32_CurrentTime Windows XP and Windows Server 2003
only
WMI Win32_LocalTime Windows XP and Windows Server 2003
only
WMI Win32_NetworkAdapterConfiguration
WMI Win32_NetworkAdapter
WMI Win32_OperatingSystem
WMI Win32_PingStatus Windows XP and Windows Server 2003
only
WMI Win32_TimeZone
WMI Win32_UTCTime Windows XP and Windows Server 2003
only
ADSI None
1 Windows 2000, Windows XP and Windows Server 2003. May also be present on other versions of Windows
Table 46 lists the registry keys for managing your network when you use advanced scripting
techniques.
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 46 Registry Subkeys for Managing Networks with Advanced Scripting Techniques
Registry SubkeysHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dhcp\Parameters\Options
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dnscache\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBT\Parameters
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetBT\Parameters\Interfaces
Automating TCP/IP Networking on ClientsPart 9: Scenario for Adding New Clients
Published: July 12, 2004
In places where network clients frequently join and leave the network, such as universities, hotels,
and convention centers, automating changes to network client configuration can reduce manual
errors and increase productivity, freeing network administrators to concentrate on more urgent
issues.
More sophisticated approaches, such as using Group Policy together with Active Directory, may
often be the best solution for handling large-scale configuration of frequently changing hosts. A
cheap, quick alternative (or complement), however, might be a script that assigns necessary
network settings to client computers that you must add to, update, or remove from a network. Such
a script would likely include settings for DHCP (or static IP), DNS, WINS, and gateway information.
You could integrate some of the script's functionality into existing logon scripts, run it separately, or
have Help Desk staff run it, depending on workflow in the organization.
Depending on the settings changed, you might need to make corresponding changes on DHCP,
DNS, and WINS servers, many of which could be automated with scripts or command-line tools.
These server-side operations are not covered in this paper.
Although this script handles only the TCP/IP settings for a client, you can easily add other client
settings, such as standard network shares or home directories. On networks that use Active
Directory, you can expand the script to use ADSI to add or modify computer and user information
within the directory.
The Script
This script adds, updates, and removes client computers from a TCP/IP network.
Caution
This script may make changes in your computer configuration. Run it only on a test computer and
note the settings involved before running it.
Input File
The script takes a text file as input, the path to which is specified in the script. In this example, the
text file is named Clients.csv. CSV stands for comma-separated values, and you can edit a .csv file
in a spreadsheet as well as a text editor. Using a spreadsheet can make creating and editing this file
much easier.
Each line of the file contains the following parameters separated by commas:
hostname, add or remove client, IP address allocation method, IP address, subnet mask, default
gateway, default gateway cost metric, DNS changes, DNS server search order, DNS hostname, DNS
domain, DNS domain suffix search order, full DNS registration enabled, domain DNS registration
enabled, WINS changes, NetBIOS TCP/IP options, DNS enabled for WINS resolution, WINS LMHOST
lookup enabled, WINS HOST lookup file, WINS scope ID, WINS primary server, WINS secondary
server
For the Clients.csv input file, Table 47 lists the file’s parameters and their type.
Table 47 Parameters for Clients.csv Input File
Parameters (in order) TypeHostname String
Add or remove client1 String
IP address allocation method2 String
IP address String array
Subnet mask String array
Default gateway String array
Default gateway cost metric Integer array
DNS changes Boolean
DNS server search order String array
Parameters (in order) Type
DNS hostname String
DNS domain String
DNS domain suffix search order String array
Full DNS registration enabled3 Boolean
Domain DNS registration enabled4 Boolean
WINS changes Boolean
NetBIOS TCP/IP options Integer
DNS enabled for WINS resolution Boolean
WINS LMHOST lookup enabled Boolean
WINS HOST lookup file String
WINS scope ID String
WINS primary server String
WINS secondary server String
1 If this parameter is set to remove, the third parameter, IP address allocation method, must be left blank; the eighth parameter, DNS changes, must be set to False or left blank; and the fifteenth parameter, WINS changes, must be set to False or left blank.
2 If this parameter is set to DHCP, the next four parameters (IP address, subnet mask, default gateway, and gateway cost metric) should be empty and marked only by the comma delimiter. If the IP address allocation method is set to static IP addressing, you must set these four parameters; and if the computer will connect to a network using DNS, you must also set the DNS server search order with the IP address of at least one DNS server.
3 If the full DNS registration enabled parameter is not set, the following parameter (domain DNS registration enabled) is ignored.
4 The domain DNS registration enabled parameter has meaning only if the previous parameter (full DNS registration enabled) is true.
For any parameters that are not set, a comma (not preceded by a space) must be used. The final
line must not be terminated with an Enter character, which would be read by the script as an empty
entry. Note that the following example contains only four lines terminated by a carriage return/line
feed: those lines begin with "client1," "client2," "newclient1," and "oldclient1," which are listed in
boldface type for legibility in this example. The second and third apparent lines are continuations of
the first, which is not ended by a carriage return/line feed. The actual second line begins with
"client2."
The script assigns the IP address allocation method for each host that is not to be removed. If the
method is static IP addressing, the script also assigns the next four parameters and the DNS server
search order. If the method is DHCP, the script does not assign any other parameters.
client1,,staticip,192.168.0.13,255.255.255.0,192.168.0.1,1,True,192.168.0.1 192.168.0.2,peter-d2,fabrikam.com,hr.fabrikam.com it.fabrikam.com,True,True,True,1,,,,,,
client2,,dhcp,,,,,False,,,,,,,False,,,,,,,
newclient1,add,staticip,192.168.0.13,255.255.255.0,192.168.0.1,1,True,192.168.0.1 192.168.0.2,peter-d2,fabrikam.com,hr.fabrikam.com it.fabrikam.com,True,True,True,1,,,,,,
oldclient1,remove,,,,,,False,,,,,,,False,,,,,,,
Scripting Steps
1. Define constants for use with the FileSystemObject.
2. Create variables to hold the paths of the input and output files and counters for the final tally.
3. Call the GetInput function, passing it the path to the input file.
4. Use the VBScript Split function to divide the returned file contents into an array of which each
element contains a line of the text file, using the line break character as the delimiter.
5. Check for the existence of the specified output file. If it exists, open it for appending so the
contents are not overwritten. If it does not exist, create it and open it.
6. Write a header for the output file containing the date and the number of computers in the
input file.
7. Iterate through the array of lines from the text file (each representing a client and its settings)
and perform the following tasks on each one.
8. Again using the Split function, divide each line of the text file into another array containing
the settings for each host, using the comma as the delimiter.
9. Read the first element of the new array, the host name, into a variable and display it.
10. Call the PingClient function, passing it the host name.
11. If the ping succeeds, connect to the WMI service on the host.
12. If no error occurs in connecting, assign the remaining 21 elements of the new array to
variables representing the settings for this host.
13. Write a heading for this host to the text file.
14. Call the GetSettings subroutine to retrieve the current settings of this host and write them to
the output file.
15. Check the second parameter from the input file for this host to determine whether TCP/IP
settings are to be updated or whether this is a client to be added or removed. Write an
appropriate header and increment the counter for clients added, removed, or updated.
16. If the network client is to be removed, call the RemoveClient subroutine.
17. Check the parameter for IP allocation to determine if DHCP or static IP settings are to be
changed. For DHCP, call the SetDHCP function. For static IP, call the SetStaticIP function.
18. Check the parameter for DNS to determine if DNS settings are to be changed. If so, call the
SetDNS subroutine.
19. Check the parameter for WINS to determine if DNS settings are to be changed. If so, first call
the SetNetBIOS function.
20. If the SetNetBIOS function is able to set NetBIOS over TCP/IP or if the setting is already as
preferred, check the value of the NetBIOS over TCP/IP setting. If the value is 1, indicating that
NetBIOS over TCP/IP is enabled, but the setting is not retrieved from the DHCP server, call the
SetWins function.
21. Again call the GetSettings subroutine, which requeries Win32_ComputerSystem and
Win32_NetworkAdapterConfiguration, retrieves the properties reflecting any changes in
settings, and writes them to the output file.
22. If the script could not connect to WMI on this host, write an error message to the output file.
23. If the ping to this host failed, write an error message to the output file.
24. Write a footer to the output file summarizing the number of clients added, removed, and
updated and any errors; and close the output file.
25. The GetInput function takes the path to the input file as a parameter. It checks whether the
specified input file exists, and if it does, opens the file and reads its contents. It returns the
text stream as a string.
26. The PingClient function takes the name of a host as a parameter. It uses the Exec method of
the WshShell object to run the command-line tool Ping.exe against the host name, parsing the
output of the tool to see if the ping was successful.
27. The GetSettings subroutine writes to the output file a range of TCP/IP client settings.
• It begins by checking the role of the computer in the domain with the DomainRole
property of the Win32_ComputerSystem class.
• It calls the GetOsVer function to verify the version of the operating system. If the version
number returned by GetOsVer is greater than 5.0 (Windows 2000), the PartOfDomain
property is available and the function retrieves it.
• Using the values of these global properties, the function writes the computer name,
domain, and domain role to the output file.
• The function iterates through the instances of the Win32_NetworkAdapterConfiguration
class for which IP is enabled and writes settings for IP allocation, DNS, NetBIOS, and WINS
to the output file.
28. The RemoveClient subroutine removes a host from the network by checking the current IP
allocation method for the client:
• If the client is using static IP addressing, the subroutine calls the EnableStatic method of
Win32_NetworkAdapterConfiguration and assigns an IP address of 0.0.0.0 and a subnet
mask of 255. 255. 255. 255.
• If the client is using DHCP, the subroutine calls the ReleaseDHCPLease method of
Win32_NetworkAdapterConfiguration to release the DHCP lease, and then calls the
EnableStatic method of Win32_NetworkAdapterConfiguration and assigns an IP address of
0.0.0.0 and a subnet mask of 255. 255. 255. 255.
29. The SetDHCP subroutine calls the EnableDHCP method of
Win32_NetworkAdapterConfiguration to enable DHCP on each IP-enabled network adapter.
30. The SetStaticIP subroutine calls the EnableStatic method of
Win32_NetworkAdapterConfiguration to disable DHPC and enable a static IP address and
subnet mask by using the input file parameters of each IP-enabled network adapter. If a static
IP address can be assigned, the subroutine then calls the SetGateways method of
Win32_NetworkAdapterConfiguration to assign default gateways and gateway cost metrics
from the input file to each IP-enabled network adapter.
31. The SetDNS subroutine assigns new DNS settings to the host. It first checks whether a new
DNS host name is assigned in the input file.
• If a new DNS host name is assigned, it calls the EnableDNS method of
Win32_NetworkAdapterConfiguration and passes it parameters for DNS host name, DNS
domain, DNS server search order, and DNS domain suffix search order.
• If no new DNS host name is to be assigned to the computer, the subroutine calls the
SetDNSDomain, SetDNSServerSearchOrder, and SetDNSSuffixSearchOrder methods of
Win32_NetworkAdapterConfiguration, passing them parameters from the input file for
these settings.
• Whether or not the computer has been assigned a new DNS host name, the subroutine
calls the SetDynamicDNSRegistration method of Win32_NetworkAdapterConfiguration,
passing it parameters from the input file for dynamic DNS registration settings.
32. The SetNetbios function changes the NetBIOS over TCP/IP setting for the host. If the current
TcpipNetbiosOptions property of the host is not equal to the setting in the input file, the
function calls the SetTCPIPNetBIOS method of Win32_NetworkAdapterConfiguration, passing it
the parameter from the input file for this setting.
33. The SetWins function changes the WINS settings on the host. It calls the EnableWINS method
of Win32_NetworkAdapterConfiguration, passing it parameters from the input file for enabling
DNS for WINS resolution, enabling LMHosts lookup, the name of the host lookup file, and WINS
scope ID. Then the function attempts to set the WINS servers for the host by calling the
SetWINSServer method of Win32_NetworkAdapterConfiguration and passing it the IP
addresses of the primary and secondary WINS servers from the input file.
34. The GetOsVer function retrieves the three left-most characters of the Version property of the
Win32_OperatingSystem class. This floating-point number is used by other code modules to
determine the operating system version, which affects whether particular functionality is
available to the script.
Listing 63 Addclients.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
On Error Resume Next
' Constants for FileSystemObject
Const FOR_READING = 1
Const FOR_WRITING = 2
Const FOR_APPENDING = 8
' Paths to input and output files. Input file must be a comma-delimited text
' file on same machine where script is to be run with name of accessible
' machine and other settings on each line.
strFileInput = "c:\scripts\clients.csv"
strFileOutput = "c:\scripts\newclients.csv"
' Counters for final tally
intAdd = 0
intUpdate = 0
intRemove = 0
intError = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
strInput = GetInput(strFileInput)
' Get computer info by breaking input stream into array at line breaks.
arrClients = Split(strInput, VbCrLf)
' Check to see if the output file exists. If so, open it for appending.
' If not, create it and open it for writing.
If objFSO.FileExists(strFileOutput) Then
Set objOutputFile = objFSO.OpenTextFile(strFileOutput, FOR_APPENDING)
Else
Automating TCP/IP Networking on ClientsPart 10: Resources for Scripting Network Management
Published: July 12, 2004These resources contain additional information and tools related to the scripting tasks described in
this white paper.
On This Page
Web Sites
Books
Magazines
Registry
Tools and Downloads
Web Sites• For hundreds of sample scripts that cover a variety of areas, see the
TechNet Script Center at
http://go.microsoft.com/fwlink/?LinkId=24771.
• For columns on beginning and intermediate scripting topics, see
TechNet “Tales from the Script” at
http://go.microsoft.com/fwlink/?LinkId=27640.
• For columns on advanced scripting topics, see the
MSDN Scripting Clinic at
http://go.microsoft.com/fwlink/?LinkId=24784.
• For documentation and downloads about VBScript and Windows Script Host, see
MSDN Windows Script at
http://go.microsoft.com/fwlink/?LinkId=298.
• For WMI documentation for developers and administrators, see the
WMI SDK, which is part of the Platform SDK, on MSDN at
http://go.microsoft.com/fwlink/?LinkId=24766.
Top of page
Books• For an introductory book on scripting, see the
Microsoft Windows 2000 Scripting Guide,
which is by the Microsoft Windows Resource Kit Scripting Team,
2003, Redmond, WA: Microsoft Press.
Note
The full text of this book is available online on the TechNet Script Center
http://go.microsoft.com/fwlink/?LinkId=24768
Top of page
Magazines• Windows & .NET Magazine at http://go.microsoft.com/fwlink/?LinkId=30007, which includes
information about the Windows Scripting Solutions newsletter.
Top of page
RegistryFor detailed information about many registry entries, see:
• The "Registry" chapter of the Windows 2000 Scripting Guide at
http://go.microsoft.com/fwlink/?LinkId=30001.
• The “Resource Kit Registry Reference for Windows Server 2003” at http://go.microsoft.com/fwlink/?
LinkId=30003.
• The Windows 2000 Server “Technical Reference to the Registry” at http://go.microsoft.com/fwlink/?
LinkId=31141.
The Windows registry contains many network-related settings. By using the System Registry WMI
provider, you can directly read and change registry settings in a script by using StdRegProv in the \
Root\Default namespace.
Table 48 lists the more important registry subkeys for scripting networking-related settings.
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 48 Registry Subkeys for Scripting Networking-Related Settings
Registry SubkeysHKEY_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
Top of page
Tools and Downloads• Windows Management Instrumentation Tester (Wbemtest.exe), which is included with all versions
of Windows that run WMI, for information about a tool that retrieves detailed information about WMI
classes, properties, and methods.
Top of page 11 of 11