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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With