Microsoft WSH and VBScript Programming for the Absolute Beginner Part 15 docx

10 279 0
Microsoft WSH and VBScript Programming for the Absolute Beginner Part 15 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

120 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition The first four calculations should be fairly easy to understand. In the first calculation, I took the value of intMyAge and added 1 to it. Similarly I subtracted 1 in the next calculation and then multiplied intMyAge times 2 in the third statement. The final calculation requires a little more explanation. You may have been surprised by this calculation’s result. At first glance, it appears that VBScript will try to solve the equation as follows: Step 1: Divide intMyAge, which is currently 74 by 5 yielding 14.8 Step 2: Add 14.8 to 3 getting 17.8. Step 3: Multiple 17.8 and 10 getting as the final result 178 However, VBScript says that the answer is actually 44.8. How could this be? The answer lies in something called the order of precedence, which tells VBScript the order in which to per- form individual calculations within an equation or expression. Table 4.6 outlines the order in which VBScript order of precedence occurs. Operator Description ^ Exponentiation - Negation * Multiplication / Division \ Integer division Mod Modulus + Addition - Subtraction Note: Operators appearing at the beginning of the table have precedence over operators appearing later in the table. TABLE 4.6 ORDER OF P RECEDENCE FOR VBSCRIPT A RITHMETIC O PERATORS Exponentiation occurs before negation. Negation occurs before multiplication, and so on. So when applied to the last calculation in the previous example, VBScript solves the equation as follows: Step 1: Multiple 3 * 10 to get 30 Step 2: Divide intMyAge by 5 to get 14.8 Step 3: Add 14.8 to 30 getting the final result of 44.8 You can add parentheses to your VBScript expressions to exercise control over the order in which individual calculations are performed. For example, you could rewrite the last expres- sion in the previous example as follows: inMyAge = ((intMyAge / 5) + 3) * 10 VBScript now performs individual calculation located within parentheses first, like this: Step 1: Divide intMyAge by 5 to get 14.8 Step 2: Add 14.8 and 3 to get 17.8 Step 3: Multiple 17.8 times 10 to get a final result of 178 Using the WSH to Work with Environment Variables Thus far, the scripts that you have worked with in this chapter have used variables that are defined by the scripts themselves. A second type of variable, known as an environment variable, is also available to your VBScripts. Windows operating systems automatically create and maintain environment variables. The two types of environment variables are user and com- puter. User environment variables are created during user login and provide information specific to the currently logged on user. Computer environment variables, on the other hand, are created based on what Windows learns about the computer; they are available at all times, as opposed to user variables, which are only available when you’re logged in to the computer. You may end up writing scripts that are designed to run when no one is logged on to the computer. This can be done using the Windows Scheduler Service to automate the execution scripts. In this case, user environment variables will not be available to your scripts and it will be up to you to make sure that your scripts do not depend on them. HINT 121 Chapter 4 • Constants, Variables, and Arrays 122 User and computer environment variables can be viewed from the Windows Environment Variables dialog. For example, on Windows XP you can access this dialog using the following procedure: 1. Click on Start. 2. Right-click on My Computer and select Properties. The System Properties dialog appears. 3. Select the Advanced property sheet. 4. Click on Environment Variables. The Environment Variables dialog appears, as shown in Figure 4.13. Examples of user environment variables include • TEMP. A folder where temporary files can be stored. • TMP. Another folder where temporary files can be stored. Examples of computer environment variables include • ComSpec. Specifies the location of the Windows shell. • NUMBER_OF_PROCESSORS. Displays a value of 1 for single processor computers. • OS. Displays the operating system’s name. • Path. Specifies the current search path. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 4.13 Examining Windows environment variables • PATHEXT. Specifies a list of extensions that identify executable files. • PROCESSOR_ARCHITECTURE. Identifies the computer’s processor type. • PROCESSOR_IDENTIFIER. Displays a detailed description of the computer’s processor. • PROCESSOR_LEVEL. Displays the processor’s stepping level. • PROCESSOR_REVISION. Displays the processor’s revision number. • TEMP. A folder in which temporary files can be stored. • TMP. Another folder in which temporary files can be stored. • Windir. Identifies the location of the Windows folder. To access environment variables, you need to use the WSH. For example, take a look at the following script: ‘************************************************************************* ‘Script Name: ComputerAnalyzer.vbs ‘Author: Jerry Ford ‘Created: 02/29/02 ‘Description: This script demonstrates how to access environment ‘variables using the WSH ‘************************************************************************* ‘Force the explicit declaration of all variables used in this script Option Explicit ‘Create a variable to store the name of the wolf Dim objWshObject ‘Set up an instance of the WScript.WshShell object Set objWshObject = WScript.CreateObject(“WScript.Shell”) ‘Use the WScript.Shell object’s ExpandEnvironmentScrings() method to view ‘environment variables MsgBox “This computer is running a version of “ & _ objWshObject.ExpandEnvironmentStrings(“%OS%”) & vbCrLf & _ “and has “ & _ objWshObject.ExpandEnvironmentStrings(“%NUMBER_OF_PROCESSORS%”) & _ “ processor(s).” 123 Chapter 4 • Constants, Variables, and Arrays 124 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition The first statement in this example creates an instance of the WSH WScript.Shell object using the WScript’s CreateObject() method. The next part of the script uses the WScript.Shell object’s ExpandEnvironmentStrings() method to display the value of specific environment variables. Working with Collections of Related Data When using variables, you can store an incredible amount of information during the exe- cution of your scripts; you’re limited only by the amount of memory available on your com- puter. However, keeping up with large numbers of variables can be difficult and may make your scripts difficult to maintain. Often, data items processed by a script have a relationship to one another. For example, if you write a script that collects a list of names from the user in order to generate a list of personal contacts, it would be more convenient to store and manage the list of names as a unit instead of as a collection of individual names. VBScript pro- vides support for arrays so that such a task can be performed. In the Real World Although the script demonstrates how to access environment variables, it really isn’t very useful. Another use for environment variables might be to validate the operating system on which the script has been started and to terminate script execution if it has been started on the wrong operating system like this: If objWshObject.ExpandEnvironmentStrings(“%OS%”) <> “Windows_NT” Then MsgBox “This script is designed to only run on “ & _ “Windows NT, 2000, XP or .NET” WScript.Quit End If In this example, the first line of code checks to see if the script is being run on an NT, 2000, XP, or .NET system. If it isn’t, then the second and third lines of code execute, informing the user of the situation and terminating the script’s execution. Definition An array is an indexed list of related data. The first element, or piece of data, stored in the array is assigned an index position of 0. The second element is assigned an index position of 1 and so on. Thus, by referring to an element’s index position, you can access its value. For example, you can think of an array as being like a collection of numbered index cards, where each card contains the name of a person who has been sent an invitation to a party. If you assigned a name of ItsMyParty to the collection of cards, you could then program- matically refer to any card in the collection as ItsMyParty(index#), where index# is the number written on the card. The ItsMyParty collection is an example of a single-dimension array. VBScript is capable of supporting array with as many as 60 dimensions. In most cases, all you’ll need to work with are single dimension arrays, so that’s where I’ll focus most of my attention. Single-Dimension Arrays To create a single-dimension array, you use the Dim statement. When used in the creation of arrays, the Dim statement has to have the following syntax: Dim ArrayName(dimensions) Dimensions is a comma-separated list of numbers that specifies the number of dimensions that make up the array. For example, the following VBScript statement can be used to create a single dimension array named ItsMyParty that can hold up to 10 names: Dim ItsMyParty(9) Notice that I used the number 9 to define an array that can hold up to 10 elements. This is because the first index number in the array is automatically set to 0, thus allowing the array to store 10 elements (that is, 0–9). After an array is defined, it can be populated with data. Because the first element stored in an array has an index of 0, its actual length is equal to the number supplied when the array is first defined, plus one. The following VBScript statements demonstrate how you can assign data to each element in the array: ItsMyParty (0) = “Jerry” ItsMyParty (1) = “Molly” ItsMyParty (2) = “William” ItsMyParty (3) = “Alexander” . . . ItsMyParty(9) = “Mary” HINT 125 Chapter 4 • Constants, Variables, and Arrays 126 As you can see, to assign a name to an element in the array, I had to specify the element’s index number. After you populate the array, you can access any array element by specifying its index number, like this: MsgBox ItsMyParty(1) In this example, ItsMyParty(1) equates to Molly. If you like the suggestions I made earlier in this chapter about naming constants and about using Hungarian Notation when creating names for your variables, then you might want to combine these two approaches when naming your arrays. For example, instead of naming an array ItsMyParty(), you might want to name it astrItsMyParty(). The first character of the name identifies that it’s an array and the next three characters identify the type of data that stored in the array. This is the naming standard that I’ll use when naming arrays throughout the rest of this book. Multiple-Dimension Arrays As I previously stated, VBScript can support arrays with as many as 60 dimensions, although one or two dimensions are usually sufficient. Let’s take a look at how to define a two-dimen- sional array, which you can think of as being like a two-column table. The first column con- tains the name of the guests invited to the party and the second column stores the guest’s phone numbers. Dim astrItsMyParty(3,1) astrItsMyParty(0,0) = “Jerry” astrItsMyParty(0,1) = “550-9933” astrItsMyParty(1,0) = “Molly” astrItsMyParty(1,1) = “550-8876” astrItsMyParty(2,0) = “William” astrItsMyParty(2,1) = “697-4443” astrItsMyParty(3,0) = “Alexander” astrItsMyParty(3,1) = “696-4344” In this example, a two-dimensional array is created that is four rows deep and two columns wide, allowing it to store up to eight pieces of data. To refer to any particular element in this two-dimensional array, you must supply both its row and column coordinates, like this: WScript.Echo astrItsMyParty(1,0) WScript.Echo astrItsMyParty(1,1) HINT Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition 127 Chapter 4 • Constants, Variables, and Arrays The first of the two previous statements refer to the Molly element. The second statement refers to the phone number associated with Molly. Another way of thinking about a two-dimensional array is to consider it a one- dimensional array made up of a collection of one-dimensional arrays. Processing Array Contents So far, in all the examples, I have accessed each array element by specifically referencing its index position. This works fine as long as the array is small, but it’s not a practical approach for processing the contents of large arrays, which may contain hundreds or thousands of entries. To handle arrays of this size, a different approach is needed. VBScript’s solution to this issue is the For Each Next loop. The syntax of the For Each Next loop is as follows: For Each element In group Statements . . . Next [element] Element is a variable that the loop uses to iterate through each array element. Group identi- fies the name of the array. Statements are the VBScripts statements that you add to process the contents of each array element. The For Each Next loop continues processing until every element in the array has been examined. The For Each Next loop lets your scripts process the entire contents of an array using just a few statements. The number of statements required does not increase based on array size. Therefore, you can use a For Each Next loop to process extremely large arrays with very little programming effort. For example, the next script defines an array named GameArray() and populates it with five elements. It then processes the entire array using just one line of code located within a For Each Next loop. ‘************************************************************************* ‘Script Name: ArrayDemo.vbs ‘Author: Jerry Ford ‘Created: 02/28/02 ‘Description: This script demonstrates how to store and retrieve data ‘using a single-dimension VBScript array. ‘************************************************************************* ‘Perform script initialization activities HINT 128 Option Explicit ‘Define variables used in the script Dim intCounter ‘Variable used to control a For Each loop Dim strMessage ‘Message to be displayed in a pop-up dialog strMessage = “The array contains the following default game “ & _ “information: “ & vbCrLf & vbCrLf Dim astrGameArray(4) ‘Define an array that can hold 5 index elements astrGameArray(0) = “Joe Blow” ‘The default username astrGameArray(1) = “Nevada” ‘A place worth visiting astrGameArray(2) = “Soda Can” ‘An interesting object astrGameArray(3) = “Barney” ‘A close friend astrGameArray(4) = “Pickle” ‘A favorite dessert For Each intCounter In astrGameArray strMessage = strMessage & intCounter & vbCrLf Next WScript.Echo strMessage If you run this script using the CScript.exe execution host, you receive the output shown in Figure 4.14. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 4.14 Iteratively processing all the contents of an array. These same few lines of code can just as easily process the array, even if it has a hundred or a thousand elements. The alternative to the For Each Next loop is to write an individual statement to access each element stored within the array, like this: ‘Display the contents of the array WScript.Echo strMessage WScript.Echo astrGameArray(0) WScript.Echo astrGameArray(1) WScript.Echo astrGameArray(2) WScript.Echo astrGameArray(3) WScript.Echo astrGameArray(4) Writing statements for individual access array contents may not seem like a lot of work in a small program, but imagine trying to process an array with 1,000 elements! Getting a Handle on the Size of Your Arrays VBScript provides you with two built-in functions that make it easier to work with arrays: • Ubound(). Returns a numeric value indicating the array’s upper bound or its highest element. • Lbound(). Returns a numeric value indicating the array’s lower bound or its lowest element. The Lbound() function isn’t really that useful because the lower bound of all VBScript arrays is always set equal to 0. On the other hand, the Ubound() function can be quite handy, especially when working with dynamic arrays. I’ll cover dynamic arrays a little later in this chapter. Lbound() is a function common to VBScript, VBA, and Visual Basic. It’s a lot more useful in VBA and Visual Basic because these programming languages allow you to specify the lower bounds of arrays. HINT 129 Chapter 4 • Constants, Variables, and Arrays For more information on how to work with the For Each Next loop, see Chapter 6, “Processing Collections of Data.” . and Arrays 124 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition The first statement in this example creates an instance of the WSH WScript.Shell object using the. 120 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition The first four calculations should be fairly easy to understand. In the first calculation, I took the value. supply both its row and column coordinates, like this: WScript.Echo astrItsMyParty(1,0) WScript.Echo astrItsMyParty(1,1) HINT Microsoft WSH and VBScript Programming for the Absolute Beginner, Second

Ngày đăng: 03/07/2014, 18:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan