SAPIEN Solutions

SAPIEN homepage
PrimalScript script editor+ide
PrimalScope script debugger
Free Tools script utilities
SAPIEN Press tech books
ScriptingAnswers.com learn+share
ScriptingOutpost.com online store
Blog.Sapien.com official blog
Contact Us

 

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.

  1. '
  2. ' ScriptingAnswers.com Essentials - by Don Jones
  3. '
  4. ' Enumeration by File
  5. ' This script demonstrates how to obtain an object And
  6. ' enumerate through child collections. It also demonstrates
  7. ' how to recurse through an object heirarchy. The
  8. ' script uses the FileSystemObject to delete all
  9. ' files and folders in a given start folder; it's a
  10. ' useful task all by itself and a great example of this
  11. ' technique

  12. Dim strStartFolder
  13. strStartFolder = "C:\Test"

  14. 'start by calling a subroutine to delete this
  15. 'folder's files and hit its subfolders
  16. DeleteFolder strStartFolder

  17. Sub DeleteFolder(strPath)

  18. Dim objFSO, objFile, objFolder
  19. Set objFSO = CreateObject("Scripting.FileSystemObject")

  20. 'enumerate through the files in the folder
  21. 'we've been given, for each file, delete it.
  22. For Each objFile In objFSO.GetFolder(strPath).Files
  23. objFile.Delete
  24. Next

  25. 'now enumerate through the subfolders in the
  26. 'folder we've been given. for each subfolder,
  27. 'we need to call this same subroutine, which
  28. 'is called recursion.
  29. For Each objFolder In objFSO.GetFolder(strPath).SubFolders
  30. DeleteFolder(objFolder.Path)
  31. Next

  32. 'now that the folder we've been given is empty,
  33. 'we can delete it
  34. objFSO.DeleteFolder(strPath)

  35. End Sub
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , , ,

Leave a Reply


Entries (RSS) and Comments (RSS).