Using VBScript and the FileSystemObject to Replace Batch Files
by Matt Childs02/21/2001
Most Windows users today are spared the agony of dealing with batch files. In fact, since the release of Windows 95, the need for batch files (which have limited functionality) has been heavily diminished. A quick scan of my WinME machine did in fact find about a dozen batch files, but they were placed there by different applications and most were used only during the installation process.
There was a time when batch files (bearing the .bat postfix) were used for everything from starting up applications to cleaning up hard drives. In fact, the MS-DOS batch language, while also limited, was the topic of several books targeted at personal computer users. You might still want to build small scripts that automate jobs for you, whether it be hard-drive cleaning, or just checking on available drive space, but today users can employ VBScript and the Windows Script Host (WSH) to create utility files that are vastly more powerful than batch files.
Starting with the Special Edition (SE) of Windows 98, Microsoft has included the built-in component called the Windows Script Host. (If you have an earlier version of Windows, you can download the latest WSH for free.) WSH is a script engine that lets you build and run scripts in the Windows environment. It's like having a batch language on steroids. The WSH can run scripts written in VBScript, Jscript, REXX, and Perl. This article will demonstrate the power of scripts written in VBScript.
Getting Started
Scripts for the WSH can be created using notepad.exe or any other standard text editor. To make them compatible with the WSH you simply need to give them a .vbs postfix. There are two versions of the engine, wscript.exe and cscript.exe. Wscript.exe is for running scripts from within the Windows environment and is the default engine. Cscript.exe is for running scripts from the command line. Later in this article, we will look at a script that searches all of the folders on a hard drive and creates a list of .bat files. This is a task you can easily perform with the Windows search function, but it demonstrates some of the more powerful aspects of VBScript.
First, to get a feel for the WSH, open a text file and enter the following code:
Dim strName
strName = "Matt"
Msgbox "Hello " + strName, vbExclamation + _
vbOKOnly, "Test Message Box"
Save it on your Windows desktop as test.vbs. Double-click on the script and you should see the following image:
Granted, this is pretty basic stuff, but it shows how easily you can put a script together and run it. You can also place scripts in the Startup folder, if you have a script that needs to run every time Windows starts.
The FileSystemObject
|
Related Reading
VBScript Pocket Reference |
One of the most powerful objects available to you in VBScript is the FileSystemObject. This object provides a hierarchical way to walk through the Windows file system and is the preferred method for opening files for input and output. The script in the "Searching Through the File System" section, below, will make use of this object, first to search a set of folders, and then to create a text file and write out the search results. To make this as flexible as possible, the script will give users the ability to have some input about where to search and also about what to name and where to locate the results' output.
The FileSystemObject allows you to create a collection of all the drives, folders, subfolders, and files on your machine. Essentially, this object builds a tree of all the operating-system storage devices on your machine, providing you with a structure that is easy to both interrogate and manipulate. The other advantage to using the FileSystemObject is that it provides an alternative to file input and output access.
When you first create the FileSystemObject, it returns an object with a collection of the drives available on your system. From there, you can instantiate objects to represent collections of folders and files on your machine. These are the objects that allow you to manipulate the data structure because you can create and copy the folders and the files. You can even delete these structures, but be extremely careful when performing any delete function on folders and files. Each collection of folders has a subfolders collection underneath it, and this structure is what makes walking through the hierarchy so simple. This structure will be demonstrated in the searching example later in this article.
The FileSystemObject also lets you create a text file or open an existing one and read data into or out of the file. This is a better method of file access than the traditional way, which involves opening a file for read/write and then specifying whether to handle it sequentially or randomly. The following code fragment shows how to create a file, then open that file for output.
Dim objFSO
Dim objStream
Set objFSO = createobject("scripting.filesystemobject")
Set objStream = objFSO.CreateTextFile("c:\test.txt", True)
objStream.Writeline strLine
In this example the file is created and the True argument tells it to overwrite another file in this location with the same name. We can then use the WriteLine method to write out lines of text to the file. You can use the ReadLine method to read in data or arguments from a text file as well. You can also use the GetFile method to attach existing files. The AtEndOfLine and AtEndOfStream properties allow you to set flags when reading and writing to and from a file. And you can use the Line and Column method to get data from specific locations within the file.
Searching Through the File System
To demonstrate how to work with the FileSystemObject, let's build a script that searches a drive for all instances of batch files, and then writes out their names, the paths, their size, and the dates they were last accessed. This provides a good look at using the TextStream object as well as handling the folders recursively to make sure that you have thoroughly searched the drive. The TextStream object lets you handle files with the FileSystemObject. Rather than opening a file for sequential or random access as you would have in the past, now the file is opened as a data stream that you can read from or write to. This is a more natural process than working with the file as if it were a collection of records. Granted, this is a function you have available to you via the Search function on the Start menu, but it's a good example of using VBScript with the FileSystemObject, and you can use the Search function to check your work.
This script is deceptively simple--which is really a trait of recursiveness. We are going to call only one subroutine, but that subroutine will be calling itself until it has run out of folders to search. Click here to view the code.
Upon completion, you should be presented with the following window:
A quick check of the search log generated by the code we have just run should present you with a text file that resembles this:
This is a basic, bare-bones script, and the normal precaution of error handling has not been taken. The FileSystemObject provides an error collection for the TextStream object that you can use to handle script errors appropriately. In addition, no user flexibility has been added into this script, though it would be easy enough to allow command-line arguments. It would also be easy to use input boxes to determine which drive to search or the criteria to limit the search.
The work in this script is done in the CheckFolders() subroutine. This subroutine is passed a collection of folders (which in this instance is the root of the current hard drive) and a TextStream object. The subroutine checks folders, then checks each file in the files collection to see if they have the .bat postfix. If any do, then the subroutine writes out the pertinent information to the text file created earlier in the script.
After all the files in the current folder have been checked, the subroutine calls itself recursively using the subfolders collection. The script will continue to drop into each layer of nested folders until it has found the end of the branch. Along the way, each file found will be checked, and if the criteria matches, a record will be written out to the log file. After the drive has been searched, a message box will alert the user that the script has finished its job and the details of the search can be found in the log file. A quick run of the Search function in WinMe netted the same results in the log file.
Download the .vbs file containing the WSH script.
Conclusion
This WSH script touches on almost all the fundamental aspects of the FileSystemObject and it shows some basic techniques (such as looping) that can be used with VBScript. It also demonstrates some powerful capabilities in only a few lines of code, using the recursion process. With a few more lines of code, this script could easily take in parameters from the user as well as provide a more robust framework for handling errors that may occur during the run-time process. Scripts such as these can be set up to run at specific time intervals or upon startup. It is easy to build a collection of scripts that can be used to perform administrative tasks and general housecleaning. Unix system administrators have long had these capabilities. VBScript and the WSH allow Windows users and system administrators to have the same level of functionality.
Matt Childs is a senior programmer/analyst with GCI, a telecommunications company in Anchorage, Alaska. Matt has experience working as an information technology specialist in a diverse set of industries, ranging from transportation to utilities. Matt holds a B.A. in history from the University of Alaska, Anchorage, and is currently pursuing a Master in Fine Arts. When not working and writing, Matt spends his time with his beautiful wife LeAndra and their three-year-old daughter Meghan.
O'Reilly & Associates recently released (January 2001) VBScript Pocket Reference, based on the best-selling VBScript in a Nutshell (May 2000).
Sample Chapter 2, Program Structure, from VBScript in a Nutshell, is available free online.
You can also look at the Table of Contents and the Full Description for VBScript Pocket Reference.
For more information, or to order the book, click here.



