Previous Page
Next Page

Verifying a File Exists

Although the approach to file management just discussed might seem easy, in many environments, you need to take a more critical approach. In other words, you must first determine whether the file exists, and if it does, you want to append to the file (not overwrite it); if it does not exist, then you want to create it. This ensures that your log file is present on each server running your script.

To check for the existence of a particular file, you use the FileExists method of FileSystemObject. Although it's true that this method complicates the script a little, it's also true that by checking for and creating a particular file as required, you add an order of magnitude to the flexibility of the script. Without further ado, take a look at the VerifyFileExists.vbs script.

VerifyFileExists.vbs

LogFile = "C:\FSO\fso.txt"
Const ForAppending = 8

Set objFSO = CreateObject("Scripting.FileSystemObject")
   If objFSO.FileExists(LogFile) Then
         Set objFile = objFSO.OpenTextFile(LogFile, ForAppending)
         objFile.Write "appending " & Now
   Else
         Set objFile = objFSO.CreateTextFile(LogFile)
             objFile.write "writing to new file " & now
   End If

Notice that this script uses code that is very similar to the BasicLog.vbs script presented earlier in this chapter in that you define your LogFile and create FileSystemObject via the CreateObject command. However, that is where the most obvious similarity ends.

In this script, you define two constants, ForWriting and ForAppending, because you might want to perform one of these operations depending on whether the log file exists. After you create FileSystemObject, you move into an If...Then...Else loop. Notice the way in which the FileExists construct is implemented:

If objFSO.FileExists(LogFile) Then

To look for the existence of a file, you use the handle to FileSystemObject that you obtained and call the FileExists method of that object. The only required parameter is the name of the file for which you want to test existence. In this case, it is the file you set equal to the variable called LogFile.

If the file does exist, you use the OpenTextFile method of FileSystemObject and specify LogFile, and then add to the file by using the ForAppending constant. Remember, when you open a file by using the OpenTextFile command, you have to specify whether you are opening it in read-only mode, appending mode, or overwriting mode. After you specify the manner in which you are opening the file, you then use the Write command to write a line to the log file. The Now function simply writes out the current date and time in a long format.

If the file is not present, you want to create the log file. This is done by using the CreateTextFile method of FileSystemObject, as shown in the following code:

Set objFile = objFSO.CreateTextFile(LogFile)

Then you use the WRITE command to write out to the file. In reality, you could have specified ForAppending and appended to the new file, but by using ForWriting, you make it a little easier to know what is actually contained in the file.

Tip

When creating a file, it is not necessary to follow the CreateTextFile method with the OpenTextFile method because VBScript is smart enough to figure you want to write to the file you just created, and it automatically opens the file for you. If you are not going to be using the file, and depending on the configuration of your script, you may want to use the Close method.


Searching ini file for misconfiguration

1.
Open the \My Documents\Microsoft Press\VBScriptSBS\Templates\FSOTemplate.vbs script in Notepad or your favorite script editor. Save it as YourNameLookFor3GB.vbs.

2.
Delete objFolder, strFolder, and colFiles from the Header section of the script, because they will not be used.

3.
Declare a variable to hold the search string. Call it strSearch, as seen below:

Dim strSearch

4.
Declare an additional variable to hold the entire text of the TestBoot.ini file. Call it strText.

Dim strText

5.
Delete the line of constants from the Reference section of the script.

6.
In the Reference section of your script, assign the path to the TestBoot.ini file to the strFile variable. You can uncomment the strFile line and assign the appropriate path. It will look something like:

strFile = "C:\fso\testBoot.ini"

7.
Assign the value "/3GB" to the strSearch variable. It is not critical where you put this, but I put it under the strFile line to keep them together. It will look like the following:

strSearch = "/3GB"

8.
Delete the strFolder line in the Reference section, because we will not be using it.

9.
Uncomment the Set objFile line. It will need no modification.

10.
Delete the Set objFolder and Set colFiles lines, because you will not use them.

11.
Use the ReadAll method from objFile and assign the text that comes back to the strText variable. It will look like the following:

strText = objFile.ReadAll

12.
Go to the Utilities folder and copy the funLookup function from the FunLookup.vbs file. Put it at the bottom of your script. The funLookup function takes two input parameters and looks like the code below. No changes are required.

Function funLookup(strText,strSearch)
Const blnInsensitive = 1
   If InStr (1,strText, strSearch,blnInsensitive) Then
         funLookup = strSearch & " was found"
   Else
         funLookup = strSearch & " was not found"
   End If
End Function

13.
Use the Echo command to print out the results of the search. Because the funLookup function takes two parameters, we will need to supply them when we call the function in the Echo command, as seen below. This line of code is placed below the line that uses the ReadAll method.

WScript.Echo funLookup(strText,strSearch)

14.
Save and run the script. It should let you know that it found the /3GB switch in the TextBoot.ini file. If this is not the case, compare your script with the \My Documents\Microsoft Press\VBScriptSBS\ch06\LookFor3GB.vbs script.

Tip

A good way to add functionality to an existing script is to add it within a subroutine. In this way, you have the option to "turn on" or "turn off" the functionality introduced within this set of code. If you mix the new code with the existing code, without keeping it separate, then your new functionality has to be complete the first time you run the script. You risk breaking your script when you do this. In the "Using SkipLine to work with malformed ini files" section, we illustrate adding new code in the form of a subroutine.


Using SkipLine to work with malformed ini files

1.
Open the LookFor3GB.vbs file in Notepad or your script editor of choice and save it as YourNameSkipLineToLookFor3GB.vbs.

2.
At the bottom of the script, under the funLookup function, add a new subroutine and call it subLook. At the same time, end the sub on a separate line. Your code will look like the following:

Sub subLook
End sub

3.
In the subroutine, declare a variable called strLine. This variable will hold the results of using the funLookup function.

Dim strLine

4.
The beginning of a normal boot.ini file begins with square brackets. Use the existing strSearch variable and assign the square bracket to it. This will be your Reference section in this subroutine.

strSearch = "["

5.
Use the OpenTextFile method to open txtFile. Assign it to the variable objFile.

Set objFile = objFSO.OpenTextFile(strFile)

6.
Use Do Until to loop through the text file until you get to the end of the text stream. While you are doing this, read a line of text and assign it to the variable strText, as seen below:

Do Until objFile.AtEndOfStream
strText = objFile.ReadLine

7.
Use the funLookup function to examine the line of text. Pass it two parameters: strText and strSearch. Hold the results that come back from the function in the variable strLine. You code will look like the following:

strLine = funLookup(strText,strSearch)

8.
Use InStr to look inside strLine for the word not. If it finds it, then get the line number and subtract one from that value. Print out a message with the line number by using the Line property. My code to do this looks like the following:

If InStr (strLine, "not") Then
   intLine = (objFile.Line -1)
   WScript.Echo intLine & _
   " not at the beginning of the ini"

9.
If the value is found, then we want to capture the line number and subtract one from it. We will save this number in the variable intLine. We then will print out a message that indicates we have found the beginning of the ini file. To do this, we will need to refer to the intLine variable outside the subroutine. We need to DIM the intLine in the Header section of the main script. We will need to close the file and then exit the subroutine.

Else
   intLine = (objFile.Line -1)
         WScript.Echo intLine & _
         " is the beginning of the ini"
   objFile.Close
   Exit Sub

10.
We then need to close out the Do Until loop and the If...Then...Else statements.

End If
   Loop

11.
Save and run your script. At this point, it should work just like it did before, because we have not yet called the subroutine.

12.
Outside of the subroutine, under the line of code where you create the file system object and above the line that uses the OpenTextFile method, use WScript.Echo to print out a message saying that you are opening the file for a second time. My code looks like the following:

WScript.Echo "opening the file a second time ..."

13.
Delete the strText = objFile.ReadAll line. Replace it with a Do Until...Loop statement. You will loop until you get to the end of the text stream. This is seen below:

Do Until objFile.AtEndOfStream

14.
Use the Line property of objFile and see if the current line is less than the line that was returned by the subroutine you just added to the script. If it is, then we want to use the SkipLine method of objFile to go to the next line. This is seen in the code below.

If objFile.Line < intLine Then
               objFile.SkipLine

15.
If, however, the Line property of objFile is the same as that returned by the subroutine, then you will want to read the line and print out a friendly message. My code to do this looks like the following:

ElseIf objFile.Line = intLine Then
               WScript.Echo "The beginning of the ini file is: "_
               & vbNewLine & Space(5)& objFile.readLine

16.
If the line number is bigger, then you will print out a message saying that the script is over and call the Quit method. This is seen below:

Else
             WScript.Echo "the script is over"
             WScript.Quit

17.
Now you will end the If...Then...Else statement and the Do Until...Loop statement.

End If
Loop

18.
On the line before the one that prints out the message saying that you are reading the file for a second time, call the subroutine by using the word subLook.

19.
Save and run your script. If your output does not look like the following, then compare it with \My Documents\Microsoft Press\VBScriptSBS\ch06\SkipLineToLookFor3GB.vbs.

1 not at the beginning of the ini
2 not at the beginning of the ini
3 not at the beginning of the ini
4 not at the beginning of the ini
5 not at the beginning of the ini
6 is the beginning of the ini
opening the file a second time ...
The beginning of the ini file is:
   [boot loader]
the script is over


Previous Page
Next Page