Enumerating a hierarchy (like files and folders)
This example uses files and folders, but really any hierarchy - such as Active Directory - uses the same technique. You’ll want to really read through this one and understand what it’s doing to be able to take advantage of it: It shows how to have a function recursively call itself in order to completely recurse a tree of objects.
- '
- ' ScriptingAnswers.com Essentials - by Don Jones
- '
- ' Enumeration by File
- ' This script demonstrates how to obtain an object And
- ' enumerate through child collections. It also demonstrates
- ' how to recurse through an object heirarchy. The
- ' script uses the FileSystemObject to delete all
- ' files and folders in a given start folder; it's a
- ' useful task all by itself and a great example of this
- ' technique
- Dim strStartFolder
- strStartFolder = "C:\Test"
- 'start by calling a subroutine to delete this
- 'folder's files and hit its subfolders
- DeleteFolder strStartFolder
- Sub DeleteFolder(strPath)
- Dim objFSO, objFile, objFolder
- Set objFSO = CreateObject("Scripting.FileSystemObject")
- 'enumerate through the files in the folder
- 'we've been given, for each file, delete it.
- For Each objFile In objFSO.GetFolder(strPath).Files
- objFile.Delete
- Next
- 'now enumerate through the subfolders in the
- 'folder we've been given. for each subfolder,
- 'we need to call this same subroutine, which
- 'is called recursion.
- For Each objFolder In objFSO.GetFolder(strPath).SubFolders
- DeleteFolder(objFolder.Path)
- Next
- 'now that the folder we've been given is empty,
- 'we can delete it
- objFSO.DeleteFolder(strPath)
- End Sub
Tags: Enumerate, hierarchy, recurse, recursion, VBScript Scripts










