Export (0) Print
Expand All

Enumerating the Files in a Folder

Microsoft® Windows® 2000 Scripting Guide

Except for a few rare cases, folders exist solely to act as storage areas for files. Sometimes these folders are required by the operating system; for example, the operating system expects to find certain files in certain folders. In other cases, folders are created as a way to help system administrators manage their computers, or as a way to help users manage their documents. System administrators might place their scripts in a folder named Scripts and their trouble-shooting tools in a folder named Diagnostic Tools; users might place their budget spreadsheets in a folder named Budgets and their payroll information in a folder named Timecards.

Of course, the fact that a folder exists is often of limited use; you must also know what files are stored within that folder. Administrators need to know whether a particular script is stored in C:\Scripts; users need to know whether a particular spreadsheet is stored in C:\Budgets.

The Folder object includes a Files property that returns a collection of all the files stored in a folder. To retrieve this collection, a script must:

  1. Create an instance of the FileSystemObject.

  2. Use the GetFolder method to bind to the appropriate folder.

  3. Set an object reference to the Files property of the folder.

  4. Use a For Each loop to enumerate all the files and their properties. (File properties available using the FileSystemObject are shown in Table 4.5.) The script does not have to bind to each file individually in order to access the file properties.

For example, the script in Listing 4.15 retrieves a collection of files found in the folder C:\FSO and then echoes the name and size (in bytes) of each file.

Listing 4.15 Retrieving Properties for Each File in a Folder

  
1
2
3
4
5
6


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\FSO")
Set colFiles = objFolder.Files
For Each objFile in colFiles
 Wscript.Echo objFile.Name, objFile.Size
Next

As with most collections, you have no control over the order in which information is returned; that is, you cannot specify that files be sorted by name, by size, or by any other criteria. If you want to sort the file collection in a particular way, you need to copy the collection to an array, a Dictionary, or a disconnected recordset and then sort the items. For more information on arrays, see "VBScript Primer" in this book. For information on disconnected recordsets, see "Creating Enterprise Scripts" in this book.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft