VBS文件长度循环

时间:2018-08-01 11:56:18

标签: loops vbscript

我有一个脚本来列出目录中的文件,包括文件的长度:

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

工作正常。我要更改的是将其转换为显式循环,然后可以添加一些内容,例如消息框。

如果我只是在MsgBox "Done"之前输入End Sub,它将出现在每个文件中。

因此,我们的想法是添加类似loop while file existsloop while Len(file)>0之类的内容。但是我不太确定语法。

2 个答案:

答案 0 :(得分:2)

为什么不这样:

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

我会这样重写您的代码:

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

这样,您可以将任何Stream对象传递到ListSizes,例如控制台(通过cscript.exe调用时):

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

还可以怀疑文件.Size(以字节为单位)而不是文件路径的长度吗?

答案 1 :(得分:0)

因此,这是解决我的问题的最佳方法:

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

通过这种解决方案,我可以同时获得文件名长度和文件大小。