Seb
Seb

Reputation: 3564

Creating a VBS file with the ability to write out to a text file

I have a VBS file that I am trying to use to determine what folders and files are in a certain directory. I believe I have the code written correctly, but whenever I try to write out the file or current directory I get a blank text document with nothing but the root directory written out. Any advice would be greatly appreciated.

Dim NewFile

Function GetFolders (strFolderPath)
Dim objCurrentFolder, colSubfolders, objFolder, files

Set objCurrentFolder = objFSO.GetFolder(strFolderPath)
Set colSubfolders = objCurrentFolder.SubFolders

For Each objFolder In colSubfolders

NewFile.WriteLine("    - " & objFolder.Path)

Set files = folder.Files
For each folderIdx In files
    NewFile.WriteLine("        - "& folderIdx.Name)
Next

Call GetFolders (objFolder.Path)

Next

End Function

Dim fso, sFolder

Set fso = CreateObject("Scripting.FileSystemObject")
sFolder = Wscript.Arguments.Item(0)
If sFolder = "" Then
  Wscript.Echo "No Folder parameter was passed"
  Wscript.Quit
End If
Set NewFile = fso.CreateTextFile(sFolder&"\FileList.txt", True)

NewFile.WriteLine(sFolder)

Call GetFolders(sFolder)

NewFile.Close

Upvotes: 1

Views: 3130

Answers (1)

AnthonyWJones
AnthonyWJones

Reputation: 189535

You haven't payed sufficient attention to your variable naming. Your script is a good example of the reason why all VBScripts should start with the line:-

Option Explicit

This would highlight all the variables that haven't been declared which in turn will point out typos and inconsistencies in variable naming. Here is how I would write it:-

Option Explicit

Dim msFolder : msFolder = Wscript.Arguments.Item(0)

If msFolder = "" Then     
    Wscript.Echo "No Folder parameter was passed"     
    Wscript.Quit     
End If

Dim mfso : Set mfso = CreateObject("Scripting.FileSystemObject")
Dim moTextStream : Set moTextStream = mfso.CreateTextFile(msFolder & "\FileList.txt", True) 

moTextStream.WriteLine(msFolder) 

WriteFolders mfso.GetFolder(msFolder)

moTextStream.Close 

Sub WriteFolders(oParentFolder) 

    Dim oFolder
    For Each oFolder In oParentFolder.SubFolders  

        moTextStream.WriteLine("    - " & oFolder.Path) 

        Dim oFile
        For Each oFile In oFolder.Files  
            moTextStream.WriteLine("        - " & oFile.Name) 
        Next 

        WriteFolders oFolder

    Next 

End Sub 

Upvotes: 2

Related Questions