Enumerating Keys and Items in a Dictionary

Microsoft® Windows® 2000 Scripting Guide

A Dictionary is designed to serve as a temporary repository for information. Any data placed in a Dictionary is not intended for permanent storage; it is simply placed in the Dictionary temporarily and then later recalled for use within the script. For example, a list of server names might be placed in the Dictionary. Later the script might need to connect to each of these servers and retrieve a specified piece of information. As a result, the information stored in the Dictionary will have to be recalled each time the script needs to connect to a new server.

The Keys and Items methods can be used to return arrays consisting of, respectively, all the keys and all the items in a Dictionary. After you have called one of these methods, you can use a For Each loop to enumerate all the keys or items in the array.

For example, the script in Listing 4.47 creates a simple Dictionary with three keys and three items. After the Dictionary has been created, the script uses the Keys method to enumerate all the keys in the Dictionary and the Items method to enumerate all the items in the Dictionary.

Listing 4.47 Enumerating Keys and Items in a Dictionary

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Printer 1", "Printing"
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
colKeys = objDictionary.Keys
For Each strKey in colKeys
 Wscript.Echo strKey
Next
colItems = objDictionary.Items
For Each strItem in colItems
 Wscript.Echo strItem
Next

When this script is run under CScript, the following output appears in the command window:

Printer 1
Printer 2
Printer 3
Printing
Offline
Printing

To display the value of a specific item, use the Item method. For example, the following code statement displays the item value (Printing) associated with the key Printer 3:

Wscript.Echo objDictionary.Item("Printer 3")