VBScript迭代设置级别的子文件夹

时间:2009-09-16 15:39:43

标签: vbscript

好的,我有一个vbscript,遍历一个目录及其子文件夹来检索文件列表。 示例:

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

现在这对于获得一个广泛的列表非常有用,但如果存在深层文件夹层次,则表现很糟糕。

所以我的问题是,有没有办法编辑脚本的这一部分,以便它只迭代一定数量的子文件夹级别?由于文件夹结构的深度,向下钻取的理想水平将是3个级别。

2 个答案:

答案 0 :(得分:13)

给你的递归调用退出条件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

答案 1 :(得分:1)

您可以通过计算路径中的反斜杠数来计算文件夹深度...如下所示:

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