List Files and Subfolders With the VBScript FileSystemObject
Scripts are (usually) small interpreted (meaning they don't get compiled) programs that you
can write using a simple text editor like Windows Notepad. VBScript stands for "Visual Basic
Script", which means it's written in Microsoft's easy to understand Visual Basic language.
The scripts are interpreted and executed by a program called the "Windows Scripting Host",
(WSH) which is installed on Windows computers by default.
It's easy to run a VBScript in the WSH, all you have to do is give the text file containing the
code a the .vbs file extension, then double-click on the file name. When you run a VBScript
it has access to the VBScript runtime objects.
To access the computer's file system, you must create a FileSystemObject with
the CreateObject method:
Set fsObj = CreateObject("Scripting.FileSystemObject")
With the FileSystemObject you can you can get the current folder property:
Set fldr = fsObj.GetFolder(".")
From the folder property, you can get the folders subfolders collection:
Set subfldrs = fldr.SubFolders
And, from the folder property, you can get the folders files collection:
Set fls = fldr.Files
With a For Each Next loop, you can loop through all the subfolders in the folder:
For Each subfldr in subfldrs
ls = ls & "[" & subfldr.name & "]" & chr(13) & Chr(10)
Next
And, with a For Each Next loop, you can loop through all the files in the folder:
For Each fl in fls
ls = ls & fl.name & chr(13) & Chr(10)
Next
In each loop the ls variable (or Dim as they call it Basic) is a text string
that we copy all the folder and file names to. Then we open a text file named "dirlist.txt",
write the string to the file, and then close the text file.
Set tf = fsObj.OpenTextFile("dirlist.txt", 2, True, True)
tf.WriteLine ls
tf.Close
Shown below is a complete script that you can use to list folders and files in the same folder
in which you place the script:
Dim fsObj, fldr, subfldr, fls, ls, fl, tf
Set fsObj = CreateObject("Scripting.FileSystemObject")
Set fldr = fsObj.GetFolder(".")
'get subfolders collection
Set subfldrs = fldr.SubFolders
'get files collection
Set fls = fldr.Files
ls = ""
For Each subfldr in subfldrs
ls = ls & "[" & subfldr.name & "]" & chr(13) & Chr(10)
Next
For Each fl in fls
ls = ls & fl.name & chr(13) & Chr(10)
Next
Set tf = fsObj.OpenTextFile("dirlist.txt", 2, True, True)
tf.WriteLine ls
tf.Close
Set fsObj = Nothing
To use the script, copy and paste the code above into a text file and save it with a file name
with the extension .vbs. When you double-click on the filename to execute the script, it will
write the file "dirlist.txt" containing a list of the folders and files in the same folder.
|