Export (0) Print
Expand All

Collections

Microsoft® Windows® 2000 Scripting Guide

Up to this point in the chapter, the scripts have been designed to retrieve the amount of free space on drive C for a specified computer. Determining free space on a single drive is a common administrative task, particularly when you are working with user workstations that are likely to have only one hard drive. Because the intention was to retrieve free disk space for only drive C, the DeviceID (a property of the Win32_LogicalDisk class) was hard-coded into the script.

Of course, other computers, including most servers, are likely to have multiple drives. For these computers, determining the free space on drive C tells only part of the story; as a system administrator, you need to know the amount of free space on drive D, drive E, and any other drives installed on the computer.

However, this creates a problem: How do you know which drives are installed on a given computer? In theory, you could check for free space on drives C through Z. But if a computer does not have, say, a drive E, the script will fail. Although you can include code designed to handle these errors and prevent the script from failing, the resulting script will be extremely long, making it difficult to read and maintain. Such a script will also be extremely inefficient; even if a computer has only a single drive, the script will nonetheless attempt to retrieve the free space on the nonexistent drives D through Z.

Fortunately, Automation objects often return information in the form of collections. Like stamp collections or coin collections, Automation collections are simply a group of related objects. For example, the script in Listing 2.8 uses the WMI method InstancesOf (line 4) to return not just a specific drive but a collection consisting of all the logical disks installed on the computer. If the computer has four drives (C, D, E, and F), the collection will have four items, one for each drive.

Listing 2.8 Using Collections

  
1
2
3
4
5
6
7
8


Const CONVERSION_FACTOR = 1048576
Computer = "atl-dc-01"
Set objWMIService = GetObject("winmgmts://" & Computer)
Set colLogicalDisk = objWMIService.InstancesOf("Win32_LogicalDisk")
For Each objLogicalDisk In colLogicalDisk
 FreeMegaBytes = objLogicalDisk.FreeSpace / CONVERSION_FACTOR
 Wscript.Echo objLogicalDisk.DeviceID & " " & Int(FreeMegaBytes)
Next

Having information returned as a collection means you do not have to guess how many drives are installed on a computer. Instead, you simply ask for the collection (all the instances of disk drives installed on the computer). After the collection has been returned, you can use a For Each loop (also known as an iteration loop) to access each individual item in the collection.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft