Partager via


Collections with Zero Items

Microsoft® Windows® 2000 Scripting Guide

It is possible for a collection to contain zero items. For example, consider this script sample, which returns the set of all tape drives installed on a computer:

Set objWMIService = GetObject("winmgmts:")
Set colTapeDrives = objWMIService.InstancesOf("Win32_TapeDrive")
For Each objTapeDrive In colTapeDrives
    Wscript.Echo objTapeDrive.Name
Next

If this script is run on a computer that does not have a tape drive, it will appear that nothing happened. In truth, the script will run as expected. However, because the computer does not have a tape drive, the resulting collection of all tape drives installed on the computer will have zero items in it.

When run on a computer without a tape drive, the script will:

  1. Connect to the WMI service.

  2. Retrieve the collection of tape drives installed on the computer.

  3. Set up a For Each loop to iterate through the entire collection, echoing the name of each individual tape drive in the collection.

    However, because no items are in the collection, the For Each loop and any commands included within that loop are not actually run. Instead, the script skips the For Each loop and picks up with the first line following the Next statement. In this sample script, however, no lines of code follow the Next statement, meaning that the script simply stops.

There is no obvious way to tell whether the script actually ran. One way to improve this script is to use the Count property to determine how many items are in the collection. For example, this script sample uses the Count property to echo the number of tape drives installed on a computer:

Set objWMIService = GetObject("winmgmts:")
Set colTapeDrives = objWMIService.InstancesOf("Win32_TapeDrive")
Wscript.Echo colTapeDrives.Count

Your script can use the Count property to determine the number of items in the collection, and then do one of two things:

  • Echo the item properties if one or more items are in the collection.

  • Echo a message such as "No tape drives are installed on this computer." if the collection contains zero items.

This script might look like the following (the use of the If-Then-Else statement is explained later in this chapter):

Set objWMIService = GetObject("winmgmts:")
Set colTapeDrives = objWMIService.InstancesOf("Win32_TapeDrive")
If colTapeDrives.Count = 0 Then
    Wscript.Echo "No tape drives are installed on this computer."
Else
    For Each objTapeDrive In colTapeDrives
        Wscript.Echo objTapeDrive.Name
    Next
End If