printfolders.vbs

Small VBScript program to walk directory tree and print them out. Feel free to copy and modify. Needed originally for my own purposes to print out a flac-file directory tree (to list artists and disc names).

Yup, starting folder is written inside the script. Feel free to implement argument handling from command line.

Note to Finnish/Swedish/German/Eastern Bloc -users: Start the program from powershell instead of CMD (by invoking cscript.exe, the same as you would from CMD). A lot of headache is avoided when printing/redirecting folder names with accented characters, to, say, a text file. When you start the program from CMD, cscript and cmd do not play nice. When started from powershell, the whole Unicode/UTF-8 -thing seems to come together without excessive usage of chcp commands and other flaky crap.

' PrintFolders.vbs
'
' TODO: last version had access problems sorted by gracefully failing 
'       when access to a folder was denied. This version has no error
'       handling whatsoever. So it will crash if it encounters folders
' 	where user has no read/traverse rights. Will implement error 
' 	handling Real Soon Now(tm).

Dim fso
Dim dummy

Set fso = CreateObject("Scripting.FileSystemObject")

' call the recursive function with:
' path to the first folder,
' nesting level,
' are we on the last item of folder list -boolean (PROTIP: in the beginning, we are not)

dummy = WalkSubs("Z:\music\lossless\", 0, False)


' Fldr is a string containg path
' Level is a variable containing how deeply nested we are
' isLast tells the function that we are on the last item on previous list
Function WalkSubs (Fldr, Level, isLast)

Dim arrPaths
Dim curFolder
Dim colFolders
Dim lastItem
Dim lastCount
Dim entry

lastItem=False

	' Get the current folder object by path
	Set curFolder = fso.GetFolder(Fldr)

	' Indent the folder name by nesting level and print it
	Wscript.Echo String(level*4," ") & curFolder.Name 
	
	' If this is last item on the previous folder collection, print extra linefeed
	if IsLast Then WScript.Echo

	If Not IsEmpty(curFolder) Then	

   		Set arrPaths = CreateObject("System.Collections.ArrayList")
		Set colFolders = curFolder.subfolders

		' Populate arrPaths-object with subfolders from current dir
		' and sort them alphabetically
		
		For Each entry In colFolders
			arrPaths.Add entry.Path
		Next
		arrPaths.Sort

		' determine if we are on the last item and pass the 
		' argument as true if we are.

		lastCount=0
		For Each entry in arrPaths
			lastCount=lastCount+1
			if lastCount = arrPaths.Count Then lastItem = True
			dummy = WalkSubs (entry, Level+1, lastItem)
		Next
	
	Else
			WScript.Echo "Folder Object Empty."
	End If
	
End Function