Hack 50 Display a Directory Tree

 < Day Day Up > 

figs/beginner.gif figs/hack50.gif

Using some simple coding, you can display a complete map of a directory structure from a command prompt .

The Explorer interface makes it easy to browse directories on a Windows machine, but it doesn't provide a simple method to document the structure of directories and their subdirectories. For troubleshooting purposes, it's helpful to know the directory structure on file servers where users store their work. This VBScript simplifies the process of documenting a directory's structure by allowing you to view such structure from the command line. Alternatively, by redirecting the output of the command to a text file, you can print a permanent record of the structure of your directories.

The Code

Type the following code into Notepad (with Word Wrap turned off) and save the file with a .vbs extension as vbtree.vbs :

 ' Show simple directory tree Option Explicit Dim sArg, oFSO Set oFSO = CreateObject("Scripting.FileSystemObject") ' Get folder (default is current directory) If Wscript.Arguments.Count > 0 Then sArg = Wscript.Arguments(0) Else sArg = "." End If sArg = oFSO.GetAbsolutePathName(sArg) ' Process entire tree (if valid folder) If oFSO.FolderExists(sArg) Then Wscript.Echo "Folder tree for:", sArg ShowTree "", oFSO.GetFolder(sArg) End If Set oFSO = Nothing Wscript.Quit(0) Sub ShowTree(sIndent, oFolder) Dim oSubFolder, ix ix = 1 For Each oSubFolder In oFolder.SubFolders Wscript.Echo sIndent & "+--" & oSubFolder.Name If ix <> oFolder.SubFolders.Count Then ShowTree sIndent & " ", oSubFolder Else ShowTree sIndent & " ", oSubFolder End If ix = ix + 1 Next End Sub 

Running the Hack

The script is hardcoded by design to display the structure of the current directory. Place the script into to directory whose structure you want to display, such as C:\data . Then, open a command prompt, change the current directory to C:\data , and type cscript vbtree.vbs to display the tree of subdirectories under the current directory (Figure 5-5). Alternatively, you can type cscript vbtree.vbs > tree.txt to redirect the output of the script to a text file for documentation purposes.

Figure 5-5. Displaying the tree of subdirectories under C:\data
figs/wsh_0505.gif

Make sure you have the latest scripting engines on the workstation from which you run this script. You can download current scripting engines from the Microsoft Scripting home page (http://msdn.microsoft.com/scripting/).

Rod Trent

 < Day Day Up > 


Windows Server Hacks
Windows Server Hacks
ISBN: 0596006470
EAN: 2147483647
Year: 2004
Pages: 163
Authors: Mitch Tulloch

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net