Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBScript to iterate through Set level of subfolders

Tags:

vbscript

Ok, Ive got a vbscript that iterates through a directory and its subfolders to retrieve a list of files. Example here:

Set FSO = CreateObject("Scripting.FileSystemObject")
ShowSubfolders FSO.GetFolder("C:\Scripts")

Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
        Wscript.Echo Subfolder.Path
        ShowSubFolders Subfolder
    Next
End Sub

Now this is great for getting an extensive list, but horrible on performance if there is a deep folder hierachy.

So my question is, is there a way to edit this part of the script so that it only iterates through a set number of levels of subfolders? Due to the depths of folder structures an ideal amount of levels to drill down into would be 3 levels.

like image 403
markdigi Avatar asked Sep 16 '09 15:09

markdigi


2 Answers

Give your recursive call an exit condition ala

Set FSO = CreateObject("Scripting.FileSystemObject")
ShowSubfolders FSO.GetFolder("C:\Scripts"), 3 

Sub ShowSubFolders(Folder, Depth)
    If Depth > 0 then
        For Each Subfolder in Folder.SubFolders
            Wscript.Echo Subfolder.Path
            ShowSubFolders Subfolder, Depth -1 
        Next
    End if
End Sub
like image 149
cmsjr Avatar answered Nov 14 '22 00:11

cmsjr


You can calculate the folder depth by counting the number of backslashes in the path...so something like the below:

Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Scripts"

Set objFolder = objFSO.GetFolder(objStartFolder)

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)
    For Each Subfolder in Folder.SubFolders
        ' FolderDepth = (Length of current folder path) - (number if backslashes in current folder path) - (number of backslahes in path you have specified for objStartFolder)
        FolderDepth = len(Subfolder.Path) - len(replace(Subfolder.Path,"\","")) - 1
        ' Specifying FolderDepth = 1 will give everything inside your objStartFolder
        If FolderDepth = 1 then
            Wscript.Echo Subfolder.Path
        End If
        ShowSubFolders Subfolder
    Next
End Sub
like image 1
Chris Avatar answered Nov 14 '22 00:11

Chris