• No results found

In this lab, you are going to modify the script created in Lab 12 to check for the exist­ ence of the log file. If the file exists, you will overwrite it. If it does not exist, you will create it.

1. Open Notepad.exe.

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. Use Windows Explorer and create a folder called FSO and a text file called Fso.txt on your C drive.

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

7. Use CreateObject to create an instance of FileSystemObject. Set it equal to a vari­ able called objFSO. Your code will look the following:

Set objFSO = CreateObject(“Scripting.FileSystemObject”)

8. Use an If…Then…Else loop to implement the FileExists method of FileSystem-

Object. In this loop, test for the existence of LogFile. If the LogFile exists, append

to it a line of text that indicates you appended to it, and use the Now function so that you know when it ran. Your code will look like the following:

If objFSO.FileExists(LogFile) Then

Set objFile = objFSO.OpenTextFile(LogFile, ForAppending) objFile.Write “appending “ & Now

Else

9. If the file does not exist, use the CreateTextFile command to create the log file. Assign the new file to the variable objFile. Your code will look like the following: Set objFile = objFSO.CreateTextFile(LogFile)

10. Use the Close method to close the LogFile variable you just created. The code will look like the following:

objFile.Close

11. Use the OpenTextFile method to open the LogFile variable for writing. Set this equal to objFile. The following code illustrates this:

Set objFile = objFSO.OpenTextFile(LogFile, ForWriting)

12. Use the Write method of objFile to write to the LogFile variable. Use the Now func­ tion to write the date and time this occurred. Use the following code as an example: objfile.write “writing to new file “ & Now

13. End the If loop. Use End If to do this.

7

Fun with Folders

In this chapter, you look at folders. Building on your work in Chapter 6, “Working with the File System,” you take the next step toward writing bulletproof scripts that examine the environment into which they are thrust, check for the existence of files and folders, and create what is needed when the requisite materials are absent. When you finish this chapter, you’ll be able to create folders, delete folders, and copy folders all from within a single VBScript. This ability in turn leads to greater network uptime, because you eradicate the various avenues of confusion.

Before You Begin

To work through the material presented in this chapter, you need to be familiar with the following concepts from earlier chapters:

■ Utilizing the FileSystemObject

■ Using the For Each...Next construction

■ Implementing constants

■ Applying Select Case constructions

After completing this chapter you will be familiar with the following: ■ How to use the FileSystemObject class to create folders

■ How to use the FileSystemObject class to list folders

■ How to use the FileSystemObject class to delete folders

■ How to use the FileSystemObject class to verify the existence of folders

Working with Folders

In your day-to-day life as a network administrator, you must create folders hundreds of times if for no other reason than to hold a bunch of files. In my life as a consultant, I am constantly creating folders that hold project data for my clients. During the year I wrote this book, I had to create more than two dozen folders to organize the support materials, labs, and scripts so that I could keep track of them and maintain versioning information.

Just the Steps

� To create a folder

1. Create a file system object by using CreateObject. 2. Use the CreateFolder command to create the folder.

Creating the Basic Folder

Creating your basic folder requires only two lines of code. The first line of code creates an instance of the FileSystemObject class by using the CreateObject method. Set the handle returned by CreateObject to a variable, which is used in turn to invoke the

CreateFolder method of FileSystemObject. The only items required by CreateFolder are

the path and name of the folder to be created. This process is illustrated in the follow­ ing code:

Set objFSO = CreateObject(“Scripting.FileSystemObject”) Set objFolder = objFSO.CreateFolder(“c:\fso”)

Suppose you need to create some folders for a number of temporary users. You decide to call the users tempUser1 through tempUser10. It would actually take a while to cre­ ate these folders for the users. However, by making some changes to the CreateBasic- Folder.vbs script, you can easily accomplish this task. The revised script, called CreateMultiFolders.vbs, follows: Option Explicit Dim numFolders Dim folderPath Dim folderPrefix Dim objFSO Dim objFolder Dim i numFolders = 10 folderPath = “C:\" folderPrefix = “TempUser" For i = 1 To numFolders

Set objFSO = CreateObject(“Scripting.FileSystemObject”)

Set objFolder = objFSO.CreateFolder(folderPath & folderPreFix & i) Next

WScript.Echo(i - 1 & “ folders created”)

Caution FSO will not create a folder unless its parent folder already exists. Thus, an attempt to create C:\tmp\tmpusers\tmpuser1 will fail unless C:\tmp\tmpusers already exists.

Header Information

The Header information section of CreateMultiFolder.vbs begins with Option Explicit to ensure that no variables are misspelled or mistakenly introduced. You then declare six variables that are used in the script. The first variable, numFolders, holds the number of folders you want to create. The next variable, folderPath, points to the location in which you will create the folders. In this instance, you are going to create 10 folders off the root of the C drive, but these values aren’t assigned until the Reference section. The next variable is folderPrefix. In this script, you assign a word or a set of characters that VBScript will use to begin the creation of the folders. The beauty of this arrangement is that you can later change the prefix easily. The variable objFSO holds the connection

to FileSystemObject, and objFolder holds the handle to the CreateFolder command. The

last variable declared is i, which is used simply as a counter.

As you can see, we did not use On Error Resume Next. When actually modifying or moving data, it is a good idea to allow errors to cause the script to fail so that data is not harmed if something goes wrong.

Reference Information

The Reference information section of the script assigns values to some of the variables declared in the Header information section. NumFolders holds the number of folders you want to create. FolderPath is used by the CreateFolder command when it comes time to create the folders. FolderPrefix is set to TempUser, which is the folder prefix you will use for each folder that gets created.

Worker Information

The Worker information section of the script begins with a For…Next loop. In this sec­ tion we use the counter i to keep track of how many folders you want to create. The number of folders created is stored in the value numFolders. At any given time, you have created i number of folders. This counting continues for each number between 1

and numFolders (inclusive).

On the second line of the Worker information section of the script, you use the Create-

Object command to create an instance of the FileSystemObject. This line is exactly the

same as all the scripts written in Chapter 6. In every situation in which you must create an instance of the FileSystemObject class, the syntax will be exactly the same: Create-

Object(“Scripting.FileSystemObject”). In most of your scripts, you’ll set the handle to

FileSystemObject equal to objFSO (although the variable can be named anything).

The third line of the Worker information section of the CreateMultiFolder.vbs script is used to actually create the folders. Note the syntax of this command:

In the script, you concatenate folderPath with folderPrefix and a counter number. This enables you to reuse the script for a multitude of purposes. In our example, you’ll cre­ ate 10 folders, named TempUser1 through TempUser10. You could just as easily change folderPrefix to ch and then create folders labeled ch1 though ch10. In a school setting, you might want to change folderPrefix to student, and thus create folders labeled student1 through student10. If you change the value of i, you can create 10,000 or more folders just as easily as you can create 10. As you can see, it is really easy to create folders using the FileSystemObject class. It can also shave hours off of lengthy setup procedures. The best thing, however, is that once the script is written and tested, you get repeatable results. It is done right every single time.

For i = 1 To numFolders

Set objFSO = CreateObject(“Scripting.FileSystemObject”)

Set objFolder = objFSO.CreateFolder(folderPath & folderPreFix & i) Next

Output Information

After you create the folders, you want confirmation that the task completed success- fully. In this script, you use WScript.Echo to let you know that the script completed suc­ cessfully. The reason you need to use i-1 in our count is that the value of i gets incremented prior to the Echo command. This is shown in the following code:

WScript.Echo(i - 1 & “ folders created”)

Quick Check

Q. What is required to create a folder?

A. A connection to FileSystemObject is required.

Q. Which command is used to create a folder?

A. The CreateFolder command is used to create a folder.

Automatic Cleanup

One cool way to use the script for creating folders is to reuse it and modify it to delete folders. The idea here is that when you use scripts to create folders and then use them to delete folders, you have basically enabled automatic cleanup after your operations are complete.

Just the Steps

� To delete a folder

1. Implement FileSystemObject by using CreateObject. 2. Use the DeleteFolder command to delete the folder.

Deleting a Folder

Deleting a folder requires a connection to FileSystemObject. Once the connection to

FileSystemObject is established, you use the DeleteFolder command to delete the folder.

This is illustrated in the following script, DeleteBasicFolder.vbs. Notice that the big dif­ ference between creating a folder and deleting a folder is that the line in which the folder is deleted does not begin with Set. Rather than include Set, you simply include

objFSO with the DeleteFolder command and then the path to the folder you will delete.

Set objFSO = CreateObject(“Scripting.FileSystemObject”) objFSO.DeleteFolder(“c:\fso”)

Deleting Multiple Folders

It is just as easy to delete multiple folders as a single folder because the syntax is the same: make a connection to FileSystemObject, and then call the DeleteFolder method. In the DeleteMultiFolders.vbs script that follows, to make the script clean up after itself, you had to make only three changes to CreateMultiFolders.vbs. Imagine how easy it would be to run CreateMultiFolders.vbs when your school year begins—and then when the school year ends, run DeleteMultiFolders.vbs with three minor modifications. What are the modifications? There are no modifications in either the Header informa­ tion or the Reference information section of the script. In the Worker information sec­ tion of the script, you delete "Set objFolder = " and then change CreateFolder to

DeleteFolder. In the Output information section of the script, you change folders cre­

ated to read folders deleted. Option Explicit Dim numFolders Dim folderPath Dim folderPrefix Dim objFSO Dim objFolder Dim i numFolders = 10 folderPath = “C:\" folderPrefix = “TempUser" For i = 1 To numFolders

objFSO.DeleteFolder(folderPath & folderPreFix & i) Next

WScript.Echo(i - 1 & “ folders deleted”)

Quick Check

Q. To delete a folder, what two components are required?

A. You need a connection to FileSystemObject, and you need to use the Delete- Folder method.

Q. What is the nice aspect of deleting folders programmatically?

A. The nice aspect of deleting folders programmatically is that you can do so by easily modifying the script used to create the folders.

Q. What are two situations in which creating folders and deleting folders program­ matically would be useful?

A. Creating folders programmatically is useful for schools that need to create a lot of student home folders at the beginning of the school year and then delete them at the end of the year. The same technique is useful for companies when they bring in temporary workers.

Binding to Folders

To gain information about the properties or attributes of a folder, you must first bind to the folder. Because the File System Object represents folders as COM (Component Object Model) objects, you must create a reference to them prior to connecting to them—that is, you must bind to them. You already know that to create or delete a folder, you have to create an instance of FileSystemObject. After you do that, you use

the GetFolder method to connect to the folder.

Just the Steps

� To bind to a folder

1. Implement the FileSystemObject by using CreateObject. 2. Specify the path to the folder.

3. Use the Set keyword to assign the path to a variable.

In the following script, you implement FileSystemObject by using CreateObject. Next, you use the GetFolder method to bind to the folder called fso found in the C drive. Set objFSO = CreateObject(“Scripting.filesystemobject”)

Set objFolder = objFSO.getfolder(“c:\fso”) WScript.Echo(“folder is bound”)

Does the Folder Exist?

Binding to a folder in and of itself is rather boring, but what if the folder does not exist? If you try to bind to a folder that does not exist, you generate an error message, and your script might fail. The “path not found” error can be prevented from occurring by using the FolderExists method. In the CreateBasicFolder_checkFirst.vbs script, you check for the existence of a folder prior to creating a new one.

By incorporating the FolderExists method into the script to create new folders, you gain the ability to delete the previous folder prior to creating a new one. The scenario for this would be creating new student folders at the beginning of a new school year. In addition, this approach could be used to create a folder for logging on a workstation. If a previous logging folder was found, that folder could be deleted to make room for a new folder. If you don’t want to delete the folder, if that folder exists, you simply omit the DeleteFolder

command from the script and modify the message displayed to the user. Set objFSO = CreateObject(“Scripting.FileSystemObject”)

If objFSO.FolderExists (“C:\fso”) Then

WScript.Echo(“folder exists and will be deleted”) objFSO.DeleteFolder (“C:\fso”)

WScript.Echo(“clean folder created”)

Set objFolder = objFSO.CreateFolder(“c:\fso”) Else

WScript.Echo(“folder does not exist and will be created”) Set objFolder = objFSO.CreateFolder(“c:\fso”)

End if

Copying Folders

Copying folders is a fundamental task in network administration. It is important for backups and for ease of management. Often the suave network administrator consoli­ dates files and folders prior to backing them up. This allows for both a more accurate backup, and in many instances a quicker backup. In many organizations, the so-called backup window is nearly closed, and getting everything backed up during the time allotted is a constant struggle. Consolidating folders can help with that problem. You use the CopyFolder method of FileSystemObject to copy folders. It is important to realize that this method also copies subfolders (even empty ones). The syntax of the

CopyFolder method follows:

Command Required Required Optional

Tip Both the source folder and the destination folder can be specified as either a local path or a UNC (Universal Naming Convention) path. The overwrite parameter is optional and will overwrite the destination folder if it is set to True.

In the following script, you copy a folder called fso that resides on the C drive to a folder called fso1 on the C drive. It is important to note that the folder does not need to exist in order for the copy process to succeed.

Set objFSO = CreateObject (“scripting.fileSystemObject”) objFSO.CopyFolder “c:\fso","C:\fso1”

You can make the script a little easier to use by creating variables to hold both the source and the destination folders. In the next script, CopyFolderExtended.vbs, you do exactly that. In addition, you create a constant called overwriteFiles that you set to

True. Note that in this next script, the destination folder, called dFolder, is located on a network share. The CopyFolderExtended.vbs script could be used by a network administrator to copy user data from the local machine to a network drive for consol­ idated backup. One bad aspect of the CopyFolder command is that it does not indicate that it is working or that it is done. To give yourself a little bit more information, you use the Now command and WScript.Echo to indicate when the command begins. In addition, after the copy operation is complete, you receive another echo with the state­ ment that the copy ended and the time.

Const OverWriteFiles = True

WScript.Echo(“ beginning copy “ & Now) sFolder = “C:\Documents and Settings" dFolder = “\\s2\fileBu"

Set objFSO = CreateObject (“scripting.fileSystemObject”) objFSO.CopyFolder sFolder, dFolder , OverWriteFiles WScript.Echo(“ending copy “ & Now)

Moving On Up

Copying folders is a very safe operation because nothing happens to the original data. Copy operations are often used for presenting a consolidated view of data (such as copying log files) or for creating redundant data for backup purposes (as in the case of VBScript book manuscripts). Moving folders, on the other hand, can be used to free up disk space, or can be used simply because two copies of the data are neither required nor desired. If a copy operation fails halfway through, you simply end up with an extra copy of half your data. If, on the other hand, a move operation fails halfway through, to have even one complete set of information, you have to go to the destination machine and move your data back. As a result, with important data, I always copy, ver­ ify, and then delete. For stuff I am not concerned about, I perform a move.

To perform a move operation, use the MoveFolder method of FileSystemObject. The next script you look at, MoveFolder.vbs, illustrates the MoveFolder method. Unlike the

CopyFolder method, MoveFolder has only two parameters: the source and the destina­

tion. The overwrite parameter, which enables overwriting an existing folder during a move operation, is not implemented. It’s common to move folders between drives, but