Managing Windows Networks Using Scripts – Part 1: The Basics

If you would like to read the other parts in this article series please go to:

This is the first of a series of articles on scripting Windows networks, and future articles will cover in detail the various aspects of this topic.


Get your copy of Windows Server Hacks!

A popular saying about empowering people is the following:

“Give a man a fish and you’ve fed him for a day; teach him how to fish and you’ve fed him for a lifetime.”

Nothing could be truer, right? Well in the busy world of the IT pro, the same is true for scripting i.e.:

“Give an admin a script and you’ve helped him solve a problem; teach him how to script and you’ve helped him do his job.”

Being able to automate daily administration tasks using scripts can make the life of an admin a lot easier. But why learn to script? Aren’t there hundreds of scripts you can download from sites like Microsoft’s Script Center Script Repository and use to meet your needs? Well yes and no. Yes, these scripts are useful, but often you’ll need to customize them to meet your exact needs or because of the particular configuration of your environment. Oftentimes you’ll wish you could modify these scripts in some way to make them do something slightly different from what the script authors had in mind, for example by combining several scripts together into a single larger script or by using the output of one script as input for another. Or you may want to modify one of these scripts to enable you to supply user input at run time. Or you may want to modify a script so it can be used as a startup or logon script. Or you may want to modify a script to make it work against a remote computer. And so on.

You’ve got to learn the basics of Windows scripting if you want to do any of these things successfully. Surprisingly, it’s not that hard once you get into it, and that’s what this series of articles is going to be about. Starting from the basics of Windows scripting, you’ll develop the understanding of how to script various different aspects of Windows networks. Eventually, you’ll be able to script tasks you’d like to automate to make your life as an admin easier. And you’ll be able to do this both by writing scripts from scratch and by customizing publicly available scripts you can download from various sources. I’ll also point you to various resources along the way that will help you learn more about Windows scripting, and introduce you to some scripting tools as well, that you may find useful.

Scripting TCP/IP Settings

Most admins use Visual Basic Script (VBScript) for writing their Windows admin scripts. VBScript is not only a powerful language, its syntax is fairly simple to learn. VBScript can also be used in conjunction with Windows Management Instrumentation (WMI) and Active Directory Services Interfaces (ADSI) to script just about any aspect of a Windows system or Active Directory-based network. We’re going to begin learning Window scripting by using VBScript with WMI to actually do something you might find useful: change the IP address of a network adapter.

Why would you want to do this? Well, I use Virtual Server and Virtual PC a lot for setting up test environments, and I often find I have to move a virtual machine (VM) running Windows Server 2003 from one virtual network to another in order to repurpose the server for some other use. That usually means I need to change the IP address on the server (and possibly the default gateway as well). Now I know you can do this by opening Network Connections in Control Panel and right-clicking on Local Area Connections and selecting Properties and selecting Internet Protocol (TCP/IP) on the General Tab and clicking Properties and entering a new IP address and clicking OK twice, but I get tired of doing that—don’t you? And yes, I could open a command prompt and use the Netsh command, but Netsh has so many different contexts and commands and parameters that I usually end up reading the Netsh help info again and again before I finally get it right.

But what we’re really trying to do here is learn how to script, so let’s see how we can change the IP address of a machine using VBScript and WMI. This means learning certain concepts along the way including objects, methods, properties, namespaces, and so on.

To begin with, we’ll run our script on the local computer:

strComputer = “.”

Here the str- prefix means strComputer is a variable that contains a string, while the period is a wildcard that refers to the local computer and is used as the starting point of the WMI namespace. What’s a WMI namespace? It’s a hierarchical collection of different classes of objects that can be used for managing various aspects of Windows computers. For example, there’s the root namespace and under it are a dozen or so namespaces including SECURITY, perfmon, CIMV2, and so on. Most WMI classes that are useful to work with are found in the root\cimv2 namespace, and before we can work with any of these classes we need to instantiate them into objects. Then we can view the properties of these objects and call their methods to manipulate them.

A Brief Detour

Classes, objects, properties, methods—what’s all this? Here’s a simple analogy that may help: consider the MicrowaveOven class. In other words, the abstract collection of all possible microwave ovens (not any one particular real oven). This class may have the following properties: Color, CubicInches, HasTurntable, and so on. Properties are things that are characteristics of a class. In other words, Microwave ovens have a certain color, a certain inside size in cubic inches, they either have turntables in them or they don’t, and so on.

The MicrowaveOven class also has methods. Methods are things the class can do or that you can do with the class. For this particular class, some methods might include SetCookingTime, SetPowerLevel, Reset, and so on. Usually to call a method you have to pass a parameter to it. For example, to call the SetCookingTime method we might define a CookingTime variable in seconds and then pass this variable to the SetCookingTime method for a particular instance of this class (an actual, real-world microwave oven—not the abstract class). In WMI VBScript you’d do this as follows:

intCookingTime = 120
errSetCookingTime = objMicrowave.SetCookingTime(intCookingTime)

But where did the Microwave object (objMicrowave) come from? We haven’t created it yet, so let’s do that by using the Set command and the CreateObject method:

Set objMicrowave = CreateObject(“MicrowaveOven”)

Actually, to be nit-pickingly accurate, objMicrowave isn’t a MicrowaveOven object. Instead, objMicrowave is an object reference to the instance of the MicrowaveOven class. But we’re just beginning here so we won’t pick too many nits.

Adding a strColor variable so we can set the color property of our microwave oven to Green, our script now looks like this (with some explanatory comments added):

strColor = “Green”   ‘specifies color
intCookingTime = 120   ‘specifies cooking time in seconds
Set objMicrowave = CreateObject(“MicrowaveOven”)   ‘creates the instance of the object
errSetCookingTime = objMicrowave.SetCookingTime(intCookingTime)   ‘calls a method to set the cooking time and saves resulting error code
objMicrowave.Color = strColor   ‘sets the value of the Color property



That all makes sense, doesn’t it?

Back To The Script

Here’s what you need to do if you want to access your machine’s TCP/IP configuration settings using WMI:

Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)

This connects you to the root\cimv2 namespace on the local computer by defining an object named objWMIService and setting it equal to the handle returned by the GetObject method. Once you’re connected to this namespace, you can gather information from it as follows:

Set colNetAdapters = objWMIService.ExecQuery(“Select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE”)”)

What does this do? First, you can see an object named objWMIService which we instantiated a moment ago in the previous line. After this object is ExecQuery, which is either a property or a method (it’s always object.property or object.method) and we can guess that it’s a method because of the wording i.e. executing a query. The ExecQuery method is called by passing a parameter to it, and this parameter is an SQL statement (SELECT) that returns a collection (the col-prefix) of all (the asterisk) network adapter configurations on the machine that have TCP/IP bound and enabled on the adapter. The collection that is returned by calling this method is then assigned to the variable colNetAdapters, which stands for the collection of all network adapters on the machine.

What can we do with this collection? When you have a collection, you must loop through it using a For Each…Next loop like this:

For Each objNetAdapter in colNetAdapters
     ‘ do something to each network adapter’s configuration
Next

You always have to loop through collections like this, even if there is only one object in the collection.

Now what we really want to do is change the IP address of our adapter, so let’s define some more variables:

arrIPAddress = Array(“172.16.11.99”)
arrSubnetMask = Array(“255.255.255.0”)

Note that the variables defining the new IP address and subnet mask need to be array variables. How do we know that? Well first, Windows computers can have more than one IP address, default gateway, and so on. So why not use array variables for all IP settings just to be consistent. And second, if we look up the Win32_NetworkAdapterConfiguration class in the WMI Reference on MSDN, we can find that this is the case. We’ll dig into the WMI Reference in future articles though, and just take my word for it for now.

Finally, we need to call the EnableStatic method of the Win32_NetworkAdapterConfiguration class in order to change the IP address and default gateway of our machine’s network adapter to the new settings we’ve defined using our array variables. We do this like this:

errEnableStatic = objNetAdapter.EnableStatic(arrIPAddress, arrSubnetMask)

Here the err- variable is needed as a place to store the error code returned when the method is run.

Bringing It All Together

Let’s put all the pieces together now and see what we’ve got:

strComputer = “.”
arrIPAddress = Array(“172.16.11.99”)
arrSubnetMask = Array(“255.255.255.0”)
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colNetAdapters = objWMIService.ExecQuery(“Select * from Win32_NetworkAdapterConfiguration”)
For Each objNetAdapter in colNetAdapters
     errEnableStatic = objNetAdapter.EnableStatic(arrIPAddress, arrSubnetMask)
Next






That’s it—minus variable definitions, error handling, use input, and confirmation output. We’ll add that stuff in the next article in this series, but first let’s see if it works. To do this, I saved the script (make sure Word Wrap is turned off in Notepad) as ChangeIPAddress.vbs and copied it to the desktop of a server who’s static IP address is 172.16.11.45. Then I opened a command prompt as Administrator and changed to the Desktop directory and ran the script using Cscript.exe, the command-line script host. Here is the result:

C:\Documents and Settings\Administrator\Desktop>ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
   Connection-specific DNS Suffix  . :
   IP Address. . . . . . . . . . . . : 172.16.11.45
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 172.16.11.1
C:\Documents and Settings\Administrator.DC-1\Desktop>


cscript ChangeIPAddress.vbs
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
C:\Documents and Settings\Administrator\Desktop>
ipconfig
Windows IP Configuration
Ethernet adapter Local Area Connection:
   Connection-specific DNS Suffix  . :
   IP Address. . . . . . . . . . . . : 172.16.11.99
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 172.16.11.1


Yep, it works! The IP address of the machine was successfully changed from .45 to .99 as the second Ipconfig command shows.

If you would like to read the other parts in this article series please go to:

About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top