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 PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. 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 *

*