Microsoft® Windows® 2000 Scripting Guide
« Previous | Next »
A dynamic array offers two advantages to script writers:
For example, you might have a script that reads computer names from a text file. Rather than guess at the number of names in the text file, you can use a dynamic array to store these names. That way, you can create an array, read in the first name, and store it as the first item in the array. If a second name happens to be in the file, you can resize the array and then read in and store the second name. You can then repeat this process until every name has been read and stored.
To create a dynamic array, you must do two things. First, when you declare the array, do not specify a maximum size. Instead, simply use empty parentheses, like this:
Dim arrTestArray()
Second, before you add a new item to the array, use the ReDim Preserve statement and increment the size of the array by 1. The ReDim Preserve statement performs two tasks:
For example, the following code sample creates a dynamic array named arrTestArray. The script creates a variable named intSize and assigns this the value 0. The script then uses the resultant line of code (intSize = 0) to resize arrTestArray so that it accepts one element (1 1 = 0).
After the script has assigned a value to the first element (item 0) in the array, ReDim Preserve is used to resize the array so that it accepts two elements (intSize + 1). A value is then assigned to the second element:
Dim arrTestArray() intSize = 0 ReDim Preserve arrTestArray(intSize) arrTestArray(intSize) =
"A
"ReDim Preserve arrTestArray(intSize + 1) arrTestArray(intSize + 1) =
"B
"
To illustrate how you might use ReDim Preserve in an actual system administration script, the following code sample retrieves a list of all the services installed on a computer and stores those service names in a dynamic array. To perform this task, the script must:
Dim arrTestArray() intSize = 0 strComputer =
".
"Set objWMIService = GetObject(
"winmgmts:
"_ &
"{impersonationLevel=impersonate}!\\
"& strComputer &
"\root\cimv2
") Set colRunningServices = objWMIService.ExecQuery _ (
"SELECT * FROM Win32_Service
") For Each objService in colRunningServices ReDim Preserve arrTestArray(intSize) arrTestArray(intSize) = objService.DisplayName intSize = intSize + 1 Next
Send us your feedback | « Previous | Next » |