VBScript: Traverse Directories & Subdirectories Snippet

This snippet has come in handy quite a few times for me…

Call ListFolderContents("C:\Windows\System32\Drivers")

Sub ListFolderContents(path)
     set fs = CreateObject("Scripting.FileSystemObject")
     set folder = fs.GetFolder(path)
         Msgbox folder.path

         For each item in folder.SubFolders
                  ListFolderContents(item.Path)
         Next
     set folder = Nothing
     set fs = Nothing
End Sub

Chrissy is a Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, and holds a number of certifications, including those relating to SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

Posted in VBScript
5 comments on “VBScript: Traverse Directories & Subdirectories Snippet
  1. peter says:

    Well, it’s an ok script for reading all the directories, but it’s unruly. You don’t destroy the objects after instantiating them, and the msgboxes will get annoying popping up constantly without any way to break out of the script. maybe something that builds an array or dictionary object to store the names in and them does one msgbox with the complete list in it.

  2. Chrissy says:

    Peter, that’s why it’s a snippet. This is a useless script on it’s own; you take it and do what you need to with it. Thanks for noticing that I didn’t kill the objects. I updated the script.

  3. Adam says:

    Thank you!

  4. Jimbo says:

    Your script would be more efficient if you only created and destroyed the FileSystemObject once. I.e:

    Dim fs
    Set fs = CreateObject(“Scripting.FileSystemObject”)
    Call ListFolderContents(“C:\Windows\System32\Drivers”)
    Set fs = Nothing

    Sub ListFolderContents(path)
    set folder = fs.GetFolder(path)
    wscript.echo folder.path

    For each item in folder.SubFolders
    ListFolderContents(item.Path)
    Next
    set folder = Nothing
    End Sub

  5. Carlos says:

    Very nice script, thanks! I was having trouble understanding how to do recursive calls within VBScript…appreciate it :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*