user9
user9

Reputation: 145

VBS file length loop

I have a script to list the files in a directory including their length:

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

Set txtOut = objFSO.CreateTextFile("d:\FileNameLength.csv")
FoldersRec "d:\MyData"

Sub FoldersRec(Startfolder)
  Set objFolder = objFSO.GetFolder(Startfolder)
  Set colSubfolders = objFolder.Subfolders

  For Each objSubfolder In colSubfolders
    FoldersRec(objSubfolder)
  Next

  For Each file In objFolder.Files
    strZeile = file & ";" & Len(file)
    txtOut.WriteLine strZeile 
  Next
  ''MsgBox "Done"
End Sub

It works fine. What I would like to change is to convert it to an explicit loop after which I can add something, like for instance a message box.

If I just enter MsgBox "Done" just before End Sub it would appear for each file.

Therefore, the idea is to add something like loop while file exists or loop while Len(file)>0. But I am not quite sure about the syntax.

Upvotes: 1

Views: 720

Answers (2)

user9
user9

Reputation: 145

So, here is the best solution for my problem:

Set fso = CreateObject("Scripting.FileSystemObject")

ListSizes fso.GetFolder("s:"), fso.CreateTextFile("r:\FileNameLength.csv")
MsgBox "Done"

Sub ListSizes(folder, outStream)
  Dim subfolder, file

  For Each subfolder In folder.Subfolders
   On Error Resume Next
   ListSizes subfolder, outStream
  Next

  For Each file In folder.Files
    outStream.WriteLine file & ";" & file.Size & ";" & len(file)
  Next      
End Sub

With this solution I get both file name length and file size.

Upvotes: 0

Tomalak
Tomalak

Reputation: 338326

Why not like this:

Set txtOut = objFSO.CreateTextFile("d:\FileNameLength.csv")
FoldersRec "d:\MyData"
MsgBox "Done"

I would rewrite your code like this:

Set fso = CreateObject("Scripting.FileSystemObject")

ListSizes fso.GetFolder("D:\MyData"), fso.CreateTextFile("d:\FileNameLength.csv")
MsgBox "Done"

Sub ListSizes(folder, outStream)
  Dim subfolder, file

  For Each subfolder In folder.Subfolders
    ListSizes subfolder, outStream
  Next
  For Each file In folder.Files
    outStream.WriteLine file & ";" & file.Size
  Next
End Sub

This way you can pass any Stream object to ListSizes, for example the console (when called through cscript.exe):

ListSizes fso.GetFolder("D:\MyData"), WScript.StdOut

Also, I suspect want the file .Size (in bytes), and not the length of the file path?

Upvotes: 2

Related Questions