Microsoft® Windows® 2000 Scripting Guide
« Previous | Next »
Recursion is a programming technique in which a subroutine or a function calls itself. You have probably seen photographs of a person staring into a mirror. In turn, his or her reflection is staring into a mirror located in the background, which reflects the person in the mirror staring into the mirror, and so on. This is the basic idea behind recursion: Subroutine A calls subroutine A, which calls subroutine A, which calls subroutine A, and so on.
Although the concept of recursion might seem a bit bizarre, it actually has important uses in system administration scripting. For example, suppose you want to enumerate all the files in a shared folder. You can easily connect to the shared root folder and list all the files, but what happens if the shared root folder has subfolders? And what happens if those subfolders contain other subfolders? Recursion allows you to enumerate all items and subitems, even if you have no advance knowledge of the folder structure.
For example, the folder structure shown in Figure 2.28 shows a root folder, Scripts, and main subfolders, Subfolder 1 and Subfolder 2. Each of those subfolders contains other subfolders.
Figure 2.28 Sample Folder Structure
Sample Folder Structure
To enumerate all the folders shown in this figure, you will have to start with the Scripts folder, return a list of subfolders, bind to each subfolder, return a list of subfolders within those folders, and so on.
To perform this task, you can use a script similar to the following. This script uses a function named ShowSubFolders that is called over and over until every folder and subfolder has been enumerated.
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
The function ShowSubFolders does the following:
When the script runs, the following output appears:
C:\scripts\Subfolder 1 C:\scripts\Subfolder 1\Subfolder 1A C:\scripts\Subfolder 1\Subfolder 1B C:\scripts\Subfolder 2 C:\scripts\Subfolder 2\Subfolder 2A C:\scripts\Subfolder 2\Subfolder 2B C:\scripts\Subfolder 2\Subfolder 2C
Recursion is an extremely powerful technique for exploring data stored in a tree structure, including Active Directory as well as the file system.
Send us your feedback | « Previous | Next » |