If...ThenIf...Then is one of those programming staples (like fried chicken and mashed potatoes are staples in the southern United States). What's nice about If...Then is that it makes sense. We use this kind of logic all the time. The basic operation is diagrammed here:
The real power of If...Then comes into play when combined with tools such as those we looked at in Chapter 2, "Looping Through the Script." If...Then is rarely used by itself. Although you could have a script such as IfThen.vbs, you wouldn't find it very valuable. On Error Resume Next Const a = 2 Const b = 3 Const c = 5 If a + b = c Then WScript.Echo(c) End If In this script three constants are defined: a, b, and c. We then sum the numbers and evaluate the result by using the If...Then statement. There are three important elements to pay attention to in implementing the If...Then construct:
If any of these elements are missing or misplaced, your If...Then statement generates an error. Make sure you remember that End If is two words, and not one word as in some other programming languages. If you do not see an error and one of these elements is missing, make sure you have commented out On Error Resume Next. Now that you have the basic syntax down pat, let's look at the following more respectable and useful script, named GetComments.vbs, which is in the folder \My Documents\Microsoft Press\VBScriptSBS\ch03. If you put lots of descriptive comments in your Microsoft Visual Basic, Scripting Edition (VBScript) scripts, Then GetComments.vbs pulls them out and writes them into a separate file. This file can be used to create a book of documentation about the most essential scripts you use in your network. In addition, If you standardize your documentation procedures, Then the created book will require very little touch-up work when you are finished. (OK, I'll quit playing If...Then with you. Let's look at that code, which is described in the next few sections.) GetComments.vbs Option Explicit On Error Resume Next Dim scriptFile Dim commentFile Dim objScriptFile Dim objFSO Dim objCommentFile Dim strCurrentLine Dim intIsComment Const ForReading = 1 Const ForWriting = 2 scriptFile = "displayComputerNames.vbs" commentFile = "comments.txt" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objScriptFile = objFSO.OpenTextFile _ (scriptFile, ForReading) Set objCommentFile = objFSO.OpenTextFile(commentFile, _ ForWriting, TRUE) Do While objScriptFile.AtEndOfStream <> TRUE strCurrentLine = objScriptFile.ReadLine intIsComment = Instr(1,strCurrentLine,"'") If intIsComment > 0 Then objCommentFile.Write strCurrentLine & VbCrLf End If Loop WScript.Echo("script complete") objScriptFile.Close objCommentFile.Close Just the Steps
Header InformationThe first few lines of the GetComments.vbs script contain the header information. We use Option Explicit to force us to declare all the variables used in the script. This helps to ensure that you spell the variables correctly as well as understand the logic. On Error Resume Next is rudimentary error handling. It tells VBScript to go to the next line in the script when there is an error. There are times, however, when you do not want this behavior, such as when you copy a file to another location prior to performing a delete operation. It would be disastrous if the copy operation failed but the delete worked. After you define the two constants, you define the variables. Listing variables on individual lines makes commenting the lines in the script easier, and the commenting lets readers of the script know why the variables are being used. In reality, it doesn't matter where you define variables, because the compiler reads the entire script prior to executing it. This means you can spread constant and variable declarations all over the script any way you wantsuch an approach would be hard for humans to read, but it would make no difference to VBScript. Reference InformationIn the Reference information section of the script, you define constants and assign values to several of the variables previously declared. The lines beginning with Const of the GetComments.vbs script define two constants, ForReading and ForWriting, which make the script easier to read. (You learned about constants in Chapter 2.) You'll use them when you open the DisplayComputerNames.vbs file and the comments.txt file from the ch03 folder on the CD. You could have just used the numbers 1 and 2 in your command and skipped the two constants; however, someone reading the script needs to know what the numbers are doing. Because these values will never change, it is more efficient to define a constant instead of using a variable. This is because the computer knows that you will only store two small numbers in these two constants. On the other hand, if we declared these two as variables, then the operating system would need to reserve enough memory to hold anything from a small number to an entire object. These varients (as they are called) are easy on programmers, but are wasteful of memory resources. But it is, after all, just a scripting language. If we were really concerned about efficiency, and conservation of resources, we would be writing in C++. The name of the file you are extracting comments from is stored in the variable scriptFile. By using the variable in this way it becomes easy to modify the script later so that you can either point it to another file or make the script read all the scripts in an entire folder. In addition, you could make the script use a command-line option that specifies the name of the script to parse for comments. However, by assigning a variable to the script file name, you make all those options possible without a whole lot of rewriting. This is also where you name the file used to write the comments intothe aptly named comments.txt file.
Worker and Output InformationThe Worker and Output information section is the core engine of the script, where the actual work is being done. You use the Set command three times, as shown here: Set objFSO = CreateObject("Scripting.FileSystemObject") Set objScriptFile = objFSO.OpenTextFile _ (scriptFile, ForReading) Set objCommentFile = objFSO.OpenTextFile(commentFile, _ ForWriting, TRUE) Regarding the first Set command, you've seen objFSO used several times already in Chapter 2. objFSO is a variable name, which we routinely assign to our connection to the file system, that allows us to read and write to files. You have to create the file system object object (as it is technically called) to be able to open text files. The second Set command uses our objScriptFile variable name to allow us to read the DisplayComputerNames.vbs file. Note that the OpenTextFile command requires only one piece of information: the name of the file. VBScript will assume you are opening the file for reading if you don't include the optional file mode information. We are going to specify two bits of information so that the script is easier to understand:
By using variables for these two parts of the OpenTextFile command, you make the script much more flexible and readable. The third Set command follows the same pattern. You assign the objCommentFile variable to whatever comes back from the openTextFile command. In this instance, however, you write to the file instead of read from it. You also use variables for the name of the comment file and for the option used to specify writing to the file. The GetComments.vbs script reads each line of the DisplayComputerNames.vbs file and checks for the presence of a single quotation mark ('). When the single quotation mark is present, the script writes the line that contains that character out to the comments.txt file. A closer examination of the Worker and Output information section of the GetComments.vbs script reveals that it begins with Do While...Loop, as shown here: Do While objScriptFile.AtEndOfStream <> TRUE strCurrentLine = objScriptFile.ReadLine intIsComment = InStr(1,strCurrentLine,"'") If intIsComment > 0 Then objCommentFile.Write strCurrentLine & vbCrLf End If Loop WScript.Echo("script complete") objScriptFile.Close objCommentFile.Close You first heard about the Do While statement in Chapter 2. ObjScriptFile contains a textStreamObject. This object was created when we used the openTextFile method from the fileSystem Object. The textStreamObject has a property that is called atEndOfStream. As long as you aren't at the end of the text stream, the script reads the line of text and sees whether it contains a single quotation mark. AtEndOfStream is a property. It describes a physical location. Of course, we do not know where AtEndOfStream is located, so we use Do While to loop around until it finds the end of the stream. To check for the presence of the <'> character, you use the InStr function, just as discussed in Chapter 2. The InStr function returns a zero when it does not find the character; when it does find the character, it returns a number representing the location in the line of text that the character was found. If InStr finds the <'> character within the line of text, the variable intIsComment holds a number that is larger than zero. Therefore, you use the If...Then construct, as shown in the following code, to write out the line to the comments.txt file: If intIsComment > 0 Then objCommentFile.Write strCurrentLine & vbCrLf End If Notice that the condition to be evaluated is contained within If...Then. If the variable intIsComment is larger than zero, you take the action on the next line. Here you use the Write command to write out the current line of the DisplayComputerNames.vbs file. Use the Timer function to see how long the script runs
After using End If, you have the Loop command on a line by itself. The Loop command belongs to the Do While construct that began the Worker and Output information section. Loop sends the script execution back to the Do While line. VBScript continues to loop through, reading the text file and looking for' marks, as long as it doesn't reach the end of the text stream. When VBScript reaches the end of the text stream from the DisplayComputerNames script, a message displays saying that you're finished processing the script. This is important, because otherwise there would be no indication that the script has concluded running. You then close your two files and the script is done. In reality, you don't need to close the files because they will automatically close once the script exits memory, but closing the files is good practice and could help to avoid problems if the script hangs. Making a decision using If...Then
|