Using AD to Retrieve Computer Names

Instead of using a text-based input file to provide computer names in a script, you can use Active Directory (AD) as the source. You might be surprised to see just how trivial the code changes are. The script IdentifySQLComputers2.vbs in Listing A highlights the modifications necessary to change IdentifySQLComputers.vbs into an AD-based script rather than a text file-based script. Let’s look at how IdentifySQLComputers2.vbs and IdentifySQLComputers.vbs differ.

At the beginning of the script, I replaced the variable named strInputFile with a new variable named strComputerContainer, as callout A shows. The strComputerContainer variable represents the distinguished name (DN) of the AD container that stores the computer account objects. Bear in mind that the container’s name will start with "ou=" instead of "cn=" if your AD computer objects are stored in an organizational unit (OU).

At callout B, I use VBScript’s GetObject function and Active Directory Service Interfaces (ADSI) to connect to the target container in AD. After making the connection, I set a filter on the container to limit the enumeration that follows to objects of type Computer. This step is optional but handy because it prevents the script from enumerating non-Computer objects in the event the container holds other object types.

Using a For Each…Next statement (aka For Each loop), I enumerate the target container, as the code at callout C shows. This code differs slightly from that in IdentifySQLComputers.vbs. In IdentifySQLComputers.vbs, I iterate through strings in an array. In this code, objContainer contains AD Computer objects, so I must retrieve the name of each Computer object.

I obtain each computer object’s name by using the Name property. Name is an ADSI helper property that every AD object exposes. The Name property returns the object’s relative distinguished name (RDN). Because RDNs are formatted as key=value pairs (e.g., cn=Dell220), I have to remove the key= portion before I can use the name in the script. I use VBScript’s Split function to split the RDN after the equals sign, and I force Split to return the second element (e.g., Dell220) by appending the (1) value to the end of the Split statement. The resulting string is stored in strComputer.

That’s all the code changes you need to make. The remainder of IdentifySQLComputers2.vbs is identical to IdentifySQLComputers.vbs.

In addition to storing computer names in a text file or retrieving them from AD, you can also specify a range of IP addresses. The article "Remote Administration with WMI," February 2003, http://www.winnetmag.com, InstantDoc ID 37596 describes how to do so.