Using Configuration Files to Control Script Execution

In this chapter you will observe as Molly learns how to use INI files (pronounced "eye 'n eye") and determines what information she will add to her INI file. You will also learn how to work with methods belonging to the VBScript run-time FileSystemObject in order to develop a procedure that can process the contents of an INI file. This will include opening the INI file, locating the appropriate section, reading its settings, and then closing the INI file.

Creating a Configuration File to Control Script Execution

One of Molly's design goals for developing the report and log analyzer scripts is to externalize as much of the configuration of the scripts as possible. Molly works with a number of applications that use INI files to store configuration settings and user preferences. From time to time, she has to edit these files, usually by following instructions provided by an application developer or as part of an effort to try and debug a problem with an application or hardware device.

For the most part, she never paid much attention to these files. However, in deciding how best to design her VBScripts, she has decided that she would like to externalize their configuration settings in much the same way that she has seen other applications use them. To this end, she has decided to create a single INI file and to store configuration settings for each of the report and log analyzer scripts that she plans on developing.

Before getting too deep into the script development process, Molly decided to spend a little time on the Internet learning more about INI files and their structure. INI or initialization files are plain ASCII text files with a .ini file extension. They have been used for years to store settings for Windows operating systems and their hardware and software applications.

INI files provide the ability to modify the behavior of an application, utility, or script without modifying its code. INI files make it easier to maintain these types of resources and prevent the possibility of introducing an error when modifying hard-coded configuration settings. In addition, INI files provide inexperienced programmers, worried about accidentally corrupting the registry, with an alternative place to store application settings.

INI files do have some disadvantages. Unlike the Windows registry, which remains a complete mystery to many people, INI files are easy to come across and delete. INI files are stored on the computer's hard drive, which means that disk I/O must occur when processing them, naturally slowing down the applications or scripts that must access them.

How INI Files Are Used

INI files are used to store customization settings and preferences. Because they are just plain ASCII text files, INI files can be created and modified by any text editor. Since the release of Windows 95, Microsoft has strongly encouraged application and hardware developers to begin storing all configuration settings in the registry. Most application developers have gone this direction. However, if you do a search on *.INI on a computer running Windows 2000 or Windows XP, for example, you will still find dozens, if not hundreds, of INI files in use.

Despite Microsoft's continued push to get application and hardware vendors to move all settings to the Windows registry, you'll find many that still use INI files. This is especially true for older hardware and software. To accommodate these older programs and devices, Microsoft has left many of its old INI files in place. This way, older applications that were written before the days of the Windows registry still have a place to store and retrieve application settings. You will find plenty of INI files in the Windows system directory. You'll also find them scattered in folders all over your hard drive.

Microsoft operating systems also make use of INI files. For example, both Windows 2000 and XP store startup information in a file called boot.ini. This INI file is referenced every time the computer starts and is used to present a list of startup options.

Microsoft also uses INI files to store configuration settings for many of its utilities and applications. For example, if you play Solitaire, you'll find that configuration settings for the application are maintained in a file called Win.ini. To demonstrate that point, you can open Win.ini and look at the settings for the Solitaire application. Close Win.ini, open the Solitaire application, and make a configuration change. When you reopen the Win.ini file and examine the settings in the [Solitaire] sections, you will see that they have changed.

  Note

You can also use applications such as Microsoft Word to modify INI files. However, word processing applications such as Microsoft Word embed a lot of hidden characters inside files, which will wreak havoc on INI files. If you use an application such as Microsoft Word to modify your INI files, be sure that you save them as plain text files.

INI File Structure

An INI file is a file that can be read from or written to by any program, utility, or script. INI files have a very specific structure and are generally processed in a top-down order. INI files are made up of one or more sections. Section names are enclosed within a pair of brackets. Sections can be placed in any order within an INI file.

Sections contain zero or more key=value pairs, which can also be placed in any order within a section. If a key=value pair is specified more than once within a section, the last instance usually overrides the previous instances.

INI files can also contain comments. Comments are labeled using the semicolon (;) character. You can also add blank lines to an INI file to improve its presentation. However, the blank spaces have no real purpose and are ignored when the INI file is processed.

The following statements demonstrate the format and structure of a small INI file.

;Sample INI file

[Section1]
key1=value1
key2=value2

As you can see, this INI file example begins with a comment. It has a single section called [Section1]. Two key=value pairs are stored within the section. Additional sections can be added as required. Typically, an INI file is named after the application executable for which it stored settings. For example, the INI file for an application named WordDoc.exe would probably be WordDoc.ini.

  Tip

Consider naming your INI files after your VBScript file names. This will make them easier to identify and manage. If you create a VBScript application that consists of a number of separate scripts, all of which share the same INI file, you might want to name an INI file after the main or first VBScript that accesses it. The most important thing is to be consistent and predictable in your naming scheme.

It's typical for an application to have one INI file, although an application certainly can have more than one. Sometimes a collection of related applications may share the same INI file. When this is the case, each application usually has its own section within the INI file. When processing the INI file, these applications search for their specific section and parse through its key=value pairs in order to extract the configuration settings they require.


Designing the Report and Log Analyzer INI File

As the first step in creating an INI file for the report and log analyzer scripts, Molly used the Windows Notepad application to create a blank file named RptLog.ini. She then added a comment and a section heading for each script that will be using the INI file, as demonstrated below.

;Report and Log Analyzer INI File

[ErrorRpt]

[DailySales]

[DailyReturns]

[DailyProduction]

Next, she began work on the Error Report section. Molly determined that she wanted to externalize the following configuration settings:

  • SourDir. The path and file name of the Error.log report
  • ReportOn. The minimum level of error messages to report on
  • EventLog. A Boolean value indicating whether or not the script should write messages in the local Windows application event log
  • DestFile. The path and file name of the summary report
  • Debug. A Boolean value indicating whether or not the script should display intermediate results in the form of pop-up dialog boxes when processing

To begin, Molly modifies the [ErrorRpt] section, as shown below.

[ErrorRpt]
SourDir=d:Order_InventoryLogsError.log
ReportOn=3
EventLog=True
DestFile=d:Order_InventoryLogsSummary.txt
Debug=False

When the VBScript that processes the Daily Error log analyzer script runs, it will look for the report file in d:Order_InventoryLogsError.log. It will only report on errors that have been assigned a severity of 3 or higher. The script will write messages to the Windows application event log when it runs. It will write its output to d:ApplicationNameSummary.txt. Finally, it will not display any debugging information.

Next, she modifies the [DailySales] section, as shown below.

[DailySales]
SourDir=d:Order_InventoryLogsDailySales.txt
ReportOn=SummaryOnly
EventLog=True
DestFile=d:Order_InventoryLogsSummary.txt
Debug=False

The only difference in the settings for this script is the modification of the SourDir key and the ReportOn key, which has been assigned a value of SummaryOnly. This value will be used to limit the data collected by the Daily Sales Report log analyzer script to just the summary information at the bottom of the report.

  Note

Each of the report and log analyzer scripts will be designed to use default configuration settings in the event that the INI file is deleted or that settings are omitted from the INI file. For example, if the ReportOn key was removed from the [DailySales] section, then the VBScript would by default process the entire file.

Molly then modifies the [DailyProduction] section.

[DailyReturns]
SourDir=d:Order_InventoryLogsDailyReturns.txt
ReportOn=SummaryOnly
Eventlog=True
DestFile=d:Order_InventoryLogsSummary.txt
Debug=False

As you can see, the only difference between this section and the [DailySales] section is the value assigned to the SourDir key.

Then Molly modifies the [DailyReturns] section, as shown below.

[DailyProduction]
SourDir=d:Order_InventoryLogsDailyProduction.txt
Eventlog=True
ReportOn=HardAndSupl
DestFile=d:Order_InventoryLogsSummary.txt
Debug=False

Again, the only difference between this and the previous sections are the SourcDir key and the ReportOn key, which is set to HardAndSupl (instructing the script to report on both the report's hardware and supplies information).

When completely assembled, the finished INI file looks like the one shown below.

;Report summary ini file

[ErrorRpt]
SourDir=d:Order_InventoryLogsError.log
ReportOn=3
EventLog=True
DestFile=d:Order_InventorySummaryRpts
Debug=False

[DailySales]
SourDir=d:Order_InventoryLogsDailySales.txt
ReportOn=SummaryOnly
EventLog=True
DestFile=d:Order_InventorySummaryRpts
Debug=False

[DailyReturns]
SourDir=d:Order_InventoryLogsDailyReturns.txt
ReportOn=SummaryOnly
EventLog=True
DestFile=d:Order_InventorySummaryRpts
Debug=False

[DailyProduction]
SourDir=d:Order_InventoryLogsDailyProduction.txt
EventLog=True
ReportOn=HardAndSupl
DestFile=d:Order_InventorySummaryRpts
Debug=False


Creating an INI File Processing Procedure

Now that Molly has designed the RptLog.ini file, she puts a copy of it in d:VBScriptsAnalyzers on the Windows 2000 Server where the order/inventory system resides. She begins work on developing a procedure that can be used to process the INI file. Later, when she begins working on each of the report and log analyzer scripts, she'll incorporate this procedure into those scripts. In order to access and process the INI file, she will have to learn how to work with the following FileSystemObject methods:

  • FileExists()
  • OpenTextFile()
  • ReadLine()
  • Close()

The first step in using methods belonging to the FileSystemObject is to set up an instance of it within your VBScript. This is done using the WScript object's CreateObject() method and by referencing it as Scripting. FileSystemObject, as demonstrated below:

Set FsoObject = WScript.CreateObject ("Scripting.FileSystemObject")

Once instantiated as shown above, you can reference the FileSystemObject within your scripts as FsoObject.

  Note

If your VBScripts will be run on a computer that uses the Windows NT, 2000, or XP operating system along with the NTFS file system, then you must take steps to make sure that you have the appropriate set of security permissions required to perform the tasks for which your VBScripts are written.

Verifying Whether the INI File Exists

The first step that you should always take when getting ready to process a file is to verify that the file exists before attempting to open it. This allows you to avoid an error if it does not exist or to create a new file if appropriate to the task at hand. To determine whether a file exists or not, use the FileSystemObject object's FileExists() method. This method has the following syntax.

ObjectReference. FileExists(FileName)

ObjectReference is the name assigned to the instance of the FileSystemObject defined within the script, and FileName is the name and path of the file whose existence is to be verified. The FileExists() method returns a value of True if the file exists and a value of False if it does not exist.

  Note

INI files can be accidentally deleted or renamed for an assortment of reasons. One way to deal with this possible situation is to work with your system administrator to tighten up Windows security permissions to prevent nonadministrators from being able to access the contents of the folder where your scripts and INI files reside. Another way of coping with this type of situation is to hard-code a set of default configuration settings whenever possible. This way, the script can still continue to execute and possibly log an error notification event message in the Windows event log to inform you of the situation.

The following VBScript statements demonstrate how to use the FileExists() method to determine where a file named Sample.ini resides in the same folders as the VBScript.

If (FsoObject.FileExists("Sample.ini ")) Then
 MsgBox "Sample.ini already exists."
Else
 MsgBox "Sample.ini does not exist."
End If
  Note

If the file whose existence is to be verified does not reside in the same folder as the VBScript, you must specify its complete path and file name.

Opening the INI File

Once you have verified that the INI file that stores the VBScript's configuration settings exists, you can open it. To open a file, use the FileSystemObject object's OpenTextFile() method. This method opens the specified file and returns a TextStream object that can be used to process the contents of the file. The TextStream object represents a file as a contiguous stream of data. The OpenTextFile() method has the following syntax.

ObjectReference.OpenTextFile(FileName, [OpenMode, [Create, [FormatType]]])

ObjectReference is the name assigned to the instance of the FileSystemObject defined within the script, and FileName is the name and path of the file to be opened. OpenMode is an optional parameter that specifies the mode in which the file should be opened and is specified using one of the numeric values shown in Table 17.1.

Table 17.1: OpenTextFile() Constants

Constant

Description

Value

ForReading

Opens or creates a file so that it can be read

1

ForWriting

Opens a new file and writes to it

2

ForAppending

Opens an existing file and appends to the end of it

8

Create is an optional Boolean parameter. When set to True, it specifies that if the specified file does not exist, it should be created. When set to False, a new file is not created if the specified file does not exist. The default is False. FormatType is an optional parameter that specifies the format of the file when a new file is created. The available options for this parameter are listed in Table 17.2.

Table 17.2: OpenTextFile() File Format Type Options

Value

Description

TristateTrue

Opens the file as Unicode

TristateFalse

Opens the file as ASCII

TristateUseDefault

Opens the file using the operating system default file type

  Note

Be especially careful when specifying whether you wish to read, write, or append to a file. If you open a file in ForWriting mode and the file already exists, its contents are reinitialized, resulting in a loss of all existing data.

The following example demonstrates how to open a file in order to write to it. In this example, the file is created if it does not exist by specifying ForWriting as its OpenMode setting. However, if the file already exists, it is instead opened using the ForAppending mode.

Dim FsoObject, strSourceFile, OpenFile
Const cForReading = 1
Const cForWriting = 2
Const cForAppending = 8
Set FsoObject = WScript.CreateObject("Scripting.FileSystemObject")
strSourceFile = "D:LogFilesDailyRpt.log"

If (FsoObject.FileExists(strSourceFile)) Then
 Set OpenFile = FsoObject.OpenTextFile(strSourceFile, cForAppending)
Else
 Set OpenFile = FsoObject.OpenTextFile(strSourceFile, cForWriting, "True")
End If
  Note

It is not possible to perform different types of operations on an open file at the same time. In other words if you open a file using the ForReading mode, you cannot switch over to ForWriting or ForAppending modes without first closing and then reopening the file again.

Reading the INI File

Once you know how to open a file and set the appropriate mode, you are ready to read, write, or append to the file. Several steps need to be taken when reading a file, as outlined below.

  • Determine whether the file contains any data
  • Read the file
  • Close the file when done

Each of these tasks will be examined in the sections that follow.

Determining Whether a File Contains Any Data

The first thing to do when opening a file is to determine whether or not it contains any data. Otherwise, there is no point in opening it and attempting to read from it. This can be done using the AtEndOfStream property, which will return a Boolean value of True if the file contains data and False if it does not.

You can also continue to check the value of the AtEndOfStream property just before performing any read operation to make sure that you have not reached the end of the file. For example, the following VBScript statements demonstrate how to determine whether a file exists and whether or not it contains any data. If the file is found to contain data, then a loop is set up to process the file, terminating when the value of AtEndOfStream becomes equal to True.

Dim FsoObject, strSourceFile, OpenFile

Const cForReading = 1
Const cForWriting = 2
Const cForAppending = 8

Set FsoObject = WScript.CreateObject("Scripting.FileSystemObject")

strSourceFile = "d:VBScriptsAnalyzersRptLog.ini"

If (FsoObject.FileExists(strSourceFile)) Then
 Set OpenFile = FsoObject.OpenTextFile(strSourceFile, cForReading)
 Do while False = OpenFile.AtEndOfStream
 ............... . .
 Loop
Else
 MsgBox strSourceFile & " does not exist."
End If

As you can see, three constants have been defined at the beginning of the example in order to make it easier to read. These three constants represent the different ways that a file can be processed by VBScript. Next an instance of the FileSystemObject is instantiated and the location of the INI file to be processed is specified. Then an If statement is executed in order to determine whether or not the INI file contains any data. If it does, then the file is opened for reading and a Do…Until loop is executed that would then contain other statements required to process the INI file. The loop will iterate until the end of the file is reached.

Reading the Entire INI File

One way to process the contents of a file requires you to use the FileSystemObject object's ReadLine() method. This method returns a string representing an entire line of output in a file. The syntax of the ReadLine() method is shown below.

ObjectReference.ReadLine()

ObjectReference is the name assigned to the instance of the FileSystemObject defined within the script.

By modifying the previous example as shown below, you can develop a procedure to process the entire contents of the RptLog.ini that was developed earlier by Molly.

Dim FsoObject, strSourceFile, OpenFile

Const cForReading = 1
Const cForWriting = 2
Const cForAppending = 8

Set FsoObject = WScript.CreateObject("Scripting.FileSystemObject")

strSourceFile = "d:VBScriptsAnalyzersRptLog.ini"

If (FsoObject.FileExists(strSourceFile)) Then
 Set OpenFile = FsoObject.OpenTextFile(strSourceFile, cForReading)
 Do while False = OpenFile.AtEndOfStream
 WScript.Echo(OpenFile.ReadLine())
 Loop
 OpenFile.Close
Else
 MsgBox strSourceFile & " does not exist."
End If

The preceding example ensures that the INI file exists and that it has data in it before beginning to read its contents a line at a time. The INI file is read from the beginning to the end of the file using the FileSystemObject object's ReadLine() method. It ends by executing the FileSystemObject object's Close() method. This method closes an open TextStream file and has the following syntax:

ObjectReference.Close( )

ObjectReference is the name assigned to the instance of the FileSystemObject defined within the script

  Note

Always use the FileSystemObject object's Close() method before allowing your VBScripts to terminate their execution. Otherwise, you run the risk of causing an error the next time you try to process the file. The reason is that the file's end-of-file maker may not get created.

If you were to save the previous VBScript statements as a script and run them against Molly's RptLog.ini file, you would see the results shown in Figure 17.1.

click to expand
Figure 17.1: Processing the entire contents of an INI file

Reading a Section of an INI File

In many cases, it may be appropriate to read and process the entire contents of an INI file at one time. For example, when more than one script shares the same INI file, as is the case in Molly's project, you need a way to selectively process a single section of the INI file at a time. The following VBScript statements demonstrate one way to achieve this goal.

Dim FsoObject, strSourceFile, OpenFile, strInputLine, intCounter

Const cForReading = 1
Const cForWriting = 2
Const cForAppending = 8

Set FsoObject = WScript.CreateObject("Scripting.FileSystemObject")

strSourceFile = "d:VBScriptsAnalyzersRptLog.ini"

If (FsoObject.FileExists(strSourceFile)) Then
 Set OpenFile = FsoObject.OpenTextFile(strSourceFile, cForReading)

 Do Until Mid(strInputLine, 1, 15) = "[DailyReturns]"
 strInputLine = OpenFile.ReadLine
 Loop

 Do Until OpenFile.AtEndOfStream = "True"
 strInputLine = OpenFile.ReadLine
 If Mid(strInputLine, 1, 1) = "[" Then
 Exit do
 End If
 WScript.Echo strInputLine
 Loop

 OpenFile.Close

Else
 MsgBox strSourceFile & " does not exist."
End If

A Do…Until loop is set up to begin the initial processing of the INI file. In the case of this example, the Do…Until loop runs until it finds the [DailyReturns] section header. This is done using the VBScript MID() function, by passing it the parameters of 1 and 15, which represent the starting and ending character position of the opening and closing brackets in the [DailyReturns] section header. When located, the Do…Until loop stops executing and a second Do…Until loop begins running. This loop executes and processes the key=value pairs stored in the [DailyReturns] section using the ReadLine() method. This loop runs until either the next section header is found (for example, by looking for the [ character as the first character in each line that follows) or the end of the file is reached (for example, when the value of AtEndOfStream equals "True").

  Note

The Mid() function is used to retrieve or parse out a specified number of characters from a script. Its syntax is shown below.

 Mid(string, StartPosition[, Length])

String represents the string from which the characters are to be parsed. StartPosition specifies the character position within the string where the parse operation should begin, and Length is an optional parameter that specifies the number of characters to be returned. If the Length parameter is omitted, then all of the characters from the start position until the end of the string are returned.

If you were to save the previous VBScript statements as a script and run it against Molly's RptLog.ini file, you would see the results shown in Figure 17.2.

click to expand
Figure 17.2: Limiting the processing of an INI file to a single section

Using the previous example as a template, you can develop a procedure that you can incorporate into the report and log analyzer scripts in order to enable them to retrieve their configuration settings from Molly's INI file.


Summary

In this chapter, you learned how to use INI files as a means of storing configuration settings for your VBScripts. This included a review of their structure and design, as well as an explanation of the steps involved in validating their existence, opening and reading one or all of the sections that make up INI files, and how to close them when done. Using the techniques presented in this chapter, you will be able to incorporate the processing of INI files within your VBScripts and to develop the report and log analyzer scripts required in the next chapter.


Part I - Introducing Microsoft VBScriptBasics

Part II - Professional Project 1 Desktop Administration Using VBScript and the WSH

Part III - Professional Project 2 Analyzing Application Logs

Part IV - Professional Project 3 Creating a Centralized Report Management Station

Part V - Professional Project 4 Reporting Application Summary Data via the Web

Part VI - Introducing Microsoft VBScriptBasics



Microsoft VBScript Professional Projects
Microsoft VBScript Professional Projects
ISBN: 1592000568
EAN: 2147483647
Year: 2005
Pages: 366

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net