An Introduction to Files and Folders in WSH - Enumerating Files and Folders
(Page 2 of 5 )
Let’s do some basic stuff. We’ll begin by listing the content of our root drive. Let’s see what folders we have there. Now would probably be a good time to take a look at the properties and methods available to us.
Methods
object.BuildPath(Path, Name)
object.GetFile(Name)
object.GetFolder(Folder)
Properties
object.Subfolders
object.Files
object.Name
object.Path
Our code construct is very simple. We’ll use the GetFolder method to get a handle on the C: folder. Then we’ll loop through the folders and return their names. The code looks something like this:
Set objFolder = objFso.GetFolder("C:")
Set colFolders = objFolder.Subfolders
For Each folder In colFolders
Wscript.Echo folder.Name
Next
The FileSystemObject’s Subfolders property returns a collection of subfolders under the path that we specify. Because collections act like objects, we have to use a Set statement. Looping a collection is very easy with VBScript’s For Each statement. It simply returns each object in a collection one at a time until they have all been used.
A simple Echo is used to display the folder name. The Name property returns a string containing the folder object’s name. If you were to run this script using Cscript.exe, you’re output should look something like this:
Documents and Settings
Program Files
RECYCLER
System Volume Information
WINDOWS
Notice that our script returned both RECYCLER and System Volume Information. Both of these are protected system folders. You can see from this quick example just how powerful this can be.
I’m using Cscript in these examples to avoid having to click OK on a bunch of message boxes. It also allows me to demonstrate my results more easily.
A little code change and we can list our files just as easily. We’ll just trade out the folder objects for file objects.
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder("C:")
Set colFiles = objFolder.Files
For Each file In colFiles
Wscript.Echo file.Name
Next
We use the GetFolder property to connect to the root folder. Then, the Files property returns a collection of files in that folder. We used the same looping technique to enumerate the files. Again, with Cscript you should see something like this:
AUTOEXEC.BAT
boot.ini
CONFIG.SYS
IO.SYS
MSDOS.SYS
NETDETECT.COM
ntldr
pagefile.sys
Again, you can see that our script easily returned several protected system files. Remember that WSH works on a low level behind most of Windows’ protection features. You can easily damage your system if you are not careful. I recommend running scripts like this against test systems or directories before actually deploying them.
Next: Working with Files and Folders >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer