2009-09-16 5 views
6

Ok, j'ai un vbscript qui itère dans un répertoire et ses sous-dossiers pour récupérer une liste de fichiers. Exemple ici:VBScript pour parcourir le niveau Set des sous-dossiers

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 

Maintenant, ce qui est excellent pour obtenir une liste exhaustive, mais horribles sur les performances s'il y a un profond dossier hierachy. Donc, ma question est, est-il un moyen d'éditer cette partie du script de sorte qu'il ne itére que par un certain nombre de niveaux de sous-dossiers? En raison de la profondeur des structures de dossiers, la quantité idéale de niveaux à explorer serait de 3 niveaux.

Répondre

13

Donnez votre appel récursif une condition de sortie 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 
0

Vous pouvez calculer la profondeur du dossier en comptant le nombre de barres obliques inverses dans le chemin ... donc quelque chose comme ci-dessous:

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 
Questions connexes