Windows Scripting: Getting a Folder's Contents

Nov 04, 2004 14:42

Using Windows Script Host (WSH), it is possible to get the listing of files and subfolders of any given folder.

The following Visual Basic code snippet gets the subfolders of the current working directory and lists them with an Echo:

Option Explicit

Dim FSO, FolderName, Folder, File, EchoText, NumFolders, I

Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
    FolderName = FSO.GetAbsolutePathName(".")
    Set Folder = FSO.GetFolder(FolderName)

NumFolders = 0
    I = 0
    EchoText = ""

For Each File In Folder.Subfolders
        NumFolders = NumFolders + 1
    Next

For Each File In Folder.Subfolders
        EchoText = EchoText & FSO.GetFileName(File)
        I = I + 1

If NumFolders <> I Then
            EchoText = EchoText & ", "
        End If
    Next

WScript.Echo "Directory Contents: " & EchoText
Save it as subfolders.vbs in a directory with at least one subfolder and run it (double-click, or highlight and press Enter) to see it in action.

In order to get a file listing (versus the subfolder listing above), the Files collection needs to be used, versus the Folders collection (Folder.Subfolders):

Option Explicit

Dim FSO, FolderName, Folder, File, EchoText, NumFolders, I

Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
    FolderName = FSO.GetAbsolutePathName(".")
    Set Folder = FSO.GetFolder(FolderName)

NumFolders = 0
    I = 0
    EchoText = ""

For Each File In Folder.Files
        NumFolders = NumFolders + 1
    Next

For Each File In Folder.Files
        EchoText = EchoText & FSO.GetFileName(File)
        I = I + 1

If NumFolders <> I Then
            EchoText = EchoText & ", "
        End If
    Next

WScript.Echo "Directory Contents: " & EchoText
Just save the above code as files.vbs in a directory and run it to see it in action. The script will display its own filename along with the listing, so if the directory is otherwise empty, the output will look like this:

Directory Contents: files.vbs

wsh scripting, scripting, geeky, programming, windows

Previous post Next post
Up