Previous Page
Next Page

Creating Files Step-by-Step Exercises

In this section, you will practice creating files. The result of this practice is essentially a code block that you can employ in other scripts to write information to a file instead of merely echoing it to the screen.

1.
Open Notepad or the script editor of your choice. Save a blank file as YourNameStepByStep.vbs.

2.
Use Option Explicit and declare the following variables: LogFile, objFSO, and objFile.

3.
Create an assignment for the variable LogFile that will hold the name and path of your log file. The code will look like the following:

LogFile = "C:\FSO\fso.txt"

4.
Open Windows Explorer and ensure a folder called FSO and a text file called Fso.txt exist on your C drive.

5.
Create a constant called ForWriting and set it equal to 2.

6.
Use CreateObject to create an instance of the FileSystemObject. Set it equal to a variable called objFSO. Your code will look like the following:

Set objFSO = CreateObject("Scripting.FileSystemObject")

7.
Use the OpenTextFile method of objFSO to open your log file for writing. Set it equal to a variable called objFile. Your code will look like the following:

Set objFile = objFSO.OpenTextFile(LogFile, ForWriting)

8.
Use the WriteLine method and the Now function to write a line to a text file called Fso.txt that indicates you are beginning your logging. The code will look like the following:

objFile.WriteLine "beginning logging " & Now

9.
Use the WriteLine method and the Now function to write a line to the text file called Fso.txt that indicates your process is continuing. Your code will look similar to this line:

objFile.WriteLine "working on process " & Now

10.
Use the WriteLine method and the Now function to indicate the logging is complete. Your code will look like the following:

objFile.WriteLine "Logging completed at " & Now

11.
Use the Close command to close out your log file. The code will look like the following:

objFile.Close

12.
Add comments to each of the variables (LogFile, objFSO, and objFile) that were added in step 2 to indicate their use in the script. Here is an example:

Dim LogFile 'holds path to the log file
Dim objFSO 'holds connection to the FileSystemObject
Dim objFile 'used by OpenTextFile command to allow writing to file

13.
Do not delete the folder or the file, because you will use them in the next lab.


Previous Page
Next Page