240 ‘Description: This script demonstrates how to create, open, and write ‘a line of text to a text file. ‘************************************************************************* ‘Initialization Section Option Explicit Dim objFso, objFileHandle, strFileName Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) strFileName = “C:\Temp\Sample.txt” ‘Main Processing Section OpenTextFile() WriteTextOutput() CloseTextFile() TerminateScript() ‘Procedure Section Function OpenTextFile() ‘If exists open it in append mode, otherwise create and open a new file If (objFso.FileExists(strFileName)) Then Set objFileHandle = objFso.OpenTextFile(strFileName, 8) Else Set objFileHandle = objFso.OpenTextFile(strFileName, 2, “True”) End If Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition End Function Function WriteTextOutput() ‘Write 3 lines of text to the text file objFileHandle.WriteLine “Once upon a time there was a little boy who” objFileHandle.WriteLine “lived in a shoe. Unfortunately it was two sizes” objFileHandle.WriteLine “too small!” End Function Function CloseTextFile() ‘Close the file when done working with it objFileHandle.Close() End Function Function TerminateScript() ‘Stop the execution of this script WScript.Quit() End Function It is very important that you always remember to close any open files before allowing your scripts to end. You do this by using the FileSystemObject object’s Close() method as shown here: objFileHandle.Close() If you forget to close a file after working with it, the file might become corrupted because the end-of-file marker has not been created for it. You can only open a file using one mode at a time. In other words, if you open a file in ForReading mode, your script cannot write new text to the file unless you first close the file and then open it again in ForWriting mode. TRAP 241 Chapter 8 • Storing and Retrieving Data 242 If you save and run this script and then open the Sample.txt file using Windows Notepad, you’ll see the output shown in Figure 8.6. Writing to Files You have a number of different options when it comes to how your VBScripts write text to files: • Writing one or more characters at a time • Writing a line at a time • Writing blank lines Writing text one or more characters at a time is good when you need to carefully format text output, such as when you want to create reports with data lined up in columns. On the other hand, writing out one line of text at a time is convenient when the format is more free form. Finally, inserting or writing blank lines into text files helps you improve the file’s appearance, such as adding space between the heading and the text in a formal report. Writing Characters To write text to a file one or more characters at a time, you need to use the FileSystemObject object’s Write() method. This method does not append a carriage return to the end of any text that it writes. If two back-to-back write operations are performed using the Write() method, for example, the text from the second write operation is inserted into the text file Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 8.6 Writing to a new or existing text file. on the same line immediately following the text written by the first write operation. To see how this works, take at look at the following example: Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) Set objFileHandle = _ objFso.OpenTextFile(“C:\Temp\Sample.txt”, 2, “True”) objFileHandle.Write(“Once upon a time there “) objFileHandle.Write(“were three little bears.”) objFileHandle.Close() If you save and run this example, you’ll see that the output added to the text file by the script is placed on the same line as shown in Figure 8.7. Writing Lines You can modify the previous example to write text output to the file a line at a time by replacing the Write() method with the WriteLine() method: Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) Set objFileHandle = _ objFso.OpenTextFile(“C:\Temp\Sample.txt”, 2, “True”) objFileHandle.WriteLine(“Once upon a time there were three little bears.”) objFileHandle.Close() If you save and run this example, you’ll find that the results are almost exactly the same as those produced by the previous example. The one difference is that the cursor is now posi- tioned at the beginning of the next row in the text file when you run this example, whereas the cursor was left at the end of the first row when you ran the previous example. This is because the WriteLine() method automatically appends a linefeed to the end of each write operation. 243 Chapter 8 • Storing and Retrieving Data Figure 8.7 Writing characters to a text file. 244 Adding Blank Lines You can add blank lines to the output generated by your VBScripts to make it look better by using the FileSystemObject object’s WriteBlankLines() method. This method executes by writing a blank line and then advancing the cursor down to the beginning of the next row in the file. The following example demonstrates how to use the FileSystemObject object’s Write- BlankLines() method: Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) Set strInputFile = objFso.GetFile(“C:\VBScriptGames\Hangman.vbs”) Set objFileHandle = _ objFso.OpenTextFile(“C:\Temp\Sample.txt”, 2, “True”) objFileHandle.WriteBlankLines(1) objFileHandle.WriteLine(“C:\VBScriptGames\Hangman.vbs Properties”) objFileHandle.WriteBlankLines(1) objFileHandle.WriteLine(“———————————————————————-”) objFileHandle.WriteBlankLines(1) objFileHandle.WriteLine(“Creation Date: “ & strInputFile.DateCreated) objFileHandle.WriteBlankLines(1) objFileHandle.WriteLine(“Last Modified: “ & strInputFile.DateLastModified) objFileHandle.WriteBlankLines(1) objFileHandle.WriteLine(“———————————————————————-”) objFileHandle.Close() Figure 8.8 shows how the Sample.txt file looks after the script has been executed. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 8.8 Blank lines improve the presentation of reports created by your VBScripts. Reading from Files VBScript makes it just about as easy to read from a file as it is to write to one. However, before you attempt to read or process the contents of a text file, you should first make sure the file has data in it. If the file has no data, opening the file and attempting to read it is pointless. You can use the TestStream object’s AtEndOfStream property to determine whether a file con- tains data. Not only should you check the AtEndOfStream property before you begin reading a file, but your script should continue to check this property before each additional read operation to make sure data is still in the file for the script to read. In other words, you need to keep checking to make sure that your script has not reached the end-of-file marker. To demonstrate how all this works, let’s build an example. For starters, create a new VBScript and add the following statements to it: Dim objFso, objFileHandle, strDisplayString Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) Set objFileHandle = objFso.OpenTextFile(“C:\Temp\Sample.txt”, 1) The first statement defines variables to be used by the script. The next statement instanti- ates the FileSystemObject. The third statement sets up an object reference to the Sample.txt file and opens it in ForReading mode. Now add the following statements to the script: Do While objFileHandle.AtEndOfStream = False strDisplayString = strDisplayString & objFileHandle.ReadLine() & vbCrLf Loop MsgBox strDisplayString The first statement sets up a Do While loop that checks on each iteration to determine whether or not the end-of-file marker has been reached. As long as the end of the file has not been reached, another line of the file is read and appended to the end of a variable named strDisplayString. Finally, close the file by adding the following statement: objFileHandle.Close If you run this script, you’ll see output similar to that shown in Figure 8.9. 245 Chapter 8 • Storing and Retrieving Data 246 This example showed you how to read an entire file, a line at a time. Other options that are available to you when reading files include • Skipping lines • Reading one or more characters at a time • Reading the entire file at one time Skipping Lines Often text reports and other files begin with some type of heading or other information that you might not be particularly interested in. In these cases, you can skip the reading of these lines using the FileSystemObject object’s Skip() and SkipLine() methods. The Skip() method allows your script to skip a specific number of characters at a time, whereas the SkipLine() allows your script to skip entire lines. To use the Skip() method, you must pass it the number of characters that you want skipped as demonstrated here: objFileHandle.Skip(25) The SkipLine() method does not accept any arguments, so it can only be used to skip one line at a time. However, by wrapping the execution of this method up within a loop, you can skip as many lines as you want as demonstrated here: For intCounter = 1 To 5 objFileHandle.SkipLine() Next Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 8.9 Creating a VBScript that reads and displays the content of text files. Reading Files Character by Character To read a file one or more characters at a time, you need to work with the FileSystemObject object’s Read() method. This might be necessary for reading files with fixed length data. For example, you might have a report file that lists a certain category or information in a col- umn that begins at character position 20 and ends at character position 30 on each line of the report. Using the Read() method, you could develop a VBScript that reads the file and pulls out only the information stored in that column for each line of the file. To get a glimpse of the Read() method in action, consider the following example. This script uses a For loop and the SkipLine() method to skip the reading of the first 5 lines of the Sample.txt file. The Skip() method skips the first 15 characters on the next line in the file (line 6). The Read() method reads the next 22 characters from the file. The file is then closed and the text that was read from the file is displayed. Dim objFso, objFileHandle, intCounter, strDisplayString Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) Set objFileHandle = objFso.OpenTextFile(“C:\Temp\Sample.txt”, 1) For intCounter = 1 To 5 objFileHandle.SkipLine() Next objFileHandle.Skip(15) strDisplayString = objFileHandle.Read(22) objFileHandle.Close MsgBox “C:\Temp\Sample.txt was created on “ & strDisplayString Reading a File All at Once Sometimes all you need to do is read an entire file in a single operation, such as when the file to be read is already formatted to produce the output that you want. You can do this using the FileSystemObject object’s ReadAll() method as demonstrated here: Dim objFso, objFileHandle, strDisplayString Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) Set objFileHandle = objFso.OpenTextFile(“C:\Temp\Sample.txt”, 1) 247 Chapter 8 • Storing and Retrieving Data 248 strDisplayString = objFileHandle.ReadAll() objFileHandle.Close() MsgBox strDisplayString As you can see, the script reads the entire file using just one ReadAll() operation and then displays what it reads using a MsgBox() statement. The output displayed when you run this script is exactly the same as that shown previously in Figure 8.9, in which the script read the entire text file a line at a time before displaying the file’s contents. Managing Files and Folders In addition to using VBScript and the WSH to read and write to and from text files, you can also use them to help administer all your files and folder. By administer , I mean to help keep them organized. Or more specifically, to automate the organization process. For example, if your computer is connected to a local area network, you can create a VBScript that makes copies of all the files it finds in certain folders and stores them on a network server. This way, if something ever happens to your original files, you can always recover by retrieving a backup copy. The FileSystemObject provides several methods for developing scripts that can automate file administration: • CopyFile() . Copies one or more files. • MoveFile() . Moves one or more files. • DeleteFile(). Deletes one or more files. • FileExists() . Determines whether or not a file exists. The FileSystemObject also provides a large collection of methods for automating folder administration: • CopyFolder() . Copies one or more folders. • MoveFolder() . Moves one or more folders. • DeleteFolder() . Deletes one or more folders. • FolderExists() . Determines whether or not a folder exists. • CreateFolder() . Creates a new folder. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition As an alternative to working with methods belonging to the FileSystemObject, you also can work with methods that jointly belong to the File and Folder objects: • Copy() . Copies a single file or folder. • Delete() . Removes a single file or folder. • Move() . Moves a single file or folder. There are a few drawbacks to these methods. First, using these methods requires that you instantiate both the FileSystemObject and the File or Folder object, which is just a little more work. Second, they work with just one file at a time as opposed to the methods belonging to the FileSystemObject, which can work on more than one file or folder at a time. Finally, because the File and Folder objects share the same methods, it’s sometimes easy to make a mistake and accidentally mess things up. For example, if you have a file and a folder in the same location with the same or a similar name, it’s easy to accidentally delete the wrong one. Copying, Moving, and Deleting Files Using the FileSystemObject object’s CopyFile() method, you can create VBScript that can copy one or more files as demonstrated in the following example: Dim objFso Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) objFso.CopyFile “C:\Temp\Sample.txt”, “C:\VBScriptGames\Sample.txt” In this example, a file named Sample.txt located in the Temp folder on the computer C: drive is copied to the VBScriptGames folder located on the C: drive. By modifying this example, as shown here, you can change the script so that it copies more than one file. Specifically, this example results in all files named Sample being copied, regardless of their file extensions. Dim objFso Set objFso = WScript.CreateObject(“Scripting.FileSystemObject”) objFso.CopyFile “C:\Temp\Sample.*”, “C:\VBScriptGames” Wildcard characters make it possible to copy, move, or delete more than one file or folder at a time. The ? and * wildcard characters enable pattern matching. The ? character is used to specify a single character match. The * character is used to match up against an unlimited number of characters. For example, specifying *.txt results in a match with all files that have a .txt file extension. Specifying sampl?.txt results in a match only with files that have a six-character- long file name, Sampl as the first five characters, and a .txt file extension. TRICK TRICK 249 Chapter 8 • Storing and Retrieving Data . using the Write() method, for example, the text from the second write operation is inserted into the text file Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure. strInputFile.DateLastModified) objFileHandle.WriteBlankLines(1) objFileHandle.WriteLine(“———————————————————————-”) objFileHandle.Close() Figure 8.8 shows how the Sample.txt file looks after the script has been executed. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure. “True”) End If Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition End Function Function WriteTextOutput() ‘Write 3 lines of text to the text file objFileHandle.WriteLine