For Each
Microsoft® Windows® 2000 Scripting Guide
The For Each statement provides a simple way to iterate through all the items in a collection. Unlike the For Next statement (discussed later in this chapter), For Each does not require you to know how many items are in the collection. Instead, it simply begins with the first item in the collection and continues until it has iterated through every item.
A typical For Each loop looks like this:
For Each objLogicalDisk In colLogicalDisk
Wscript.Echo objLogicalDisk.DeviceID
Next
The individual items that make up this loop are described in Table 2.2.
Table 2.2 Components of the For Each Statement
Item |
Description |
---|---|
objLogicalDisk |
Variable name representing the individual disk drive instances. |
colLogicalDisk |
Variable name given to the collection of disk drives retrieved using WMI. |
For Each objLogicalDisk in colLogicalDisk |
Starts the loop. The basic syntax can be read as "For Each instance of an object in a collection of objects " do something. In this example, this can be read as "For each individual disk drive in the collection of disk drives installed on this computer " |
Wscript.Echo objLogicalDisk.DeviceID |
Commands carried out for each disk drive in the collection. (This example has only one command, but any number of lines of code are permitted between the For Each and Next statements.) Notice that individual disk drives are referenced using the variable objLogicalDisk and the appropriate property (in this case, DeviceID). The value of this property will change each time through the loop. For example, on a computer with drives C, D, and E, objLogicalDisk.DeviceID will equal C on the first iteration because C is the DeviceID for the first drive in the collection. On subsequent passes through the loop, objLogicalDisk.DeviceID will equal D and then E. |
Next |
Indicates the end of the loop. |
When working with collections, you typically iterate through the entire collection rather than refer to a single item within the collection. For example, suppose your collection consists of disk drives C, D, E, F, and G, and you want to echo only the available drive space on drive G. To do this, you will have to set up a For Each loop and begin iterating through the set of disk drives. For each drive in the collection, you can check the drive letter, and echo the available space only for drive G.
Tip
- There is no straightforward way to avoid iterating through the entire collection. However, you can make your scripts more efficient by limiting the number of items in the collection. For example, your WMI query can specify that data should be returned only for instances of the Win32_DiskDrive class in which the drive letter is equal to G. The script still returns a collection, and you still have to iterate all the items within that collection. In this case, however, the collection contains just one item, making that iteration much faster and more efficient.