在VBScript中,我想获取按创建日期排序的文件夹中的文件列表。我看到为了做到这一点,我需要使用一个记录集(对我来说似乎有点过分)或自己对集合进行排序(我想我可以避免它,我希望我的代码更短)。
由于我是创建文件的人,因此我使用以日期(yyyy_mm_dd)开头的名称创建它们,所以尽管如此我可以获得至少按名称排序的文件,然后我就完成了设置。不幸的是,MSDN documentation of the Files collection from FileSystemObject没有说明集合的顺序。有没有人知道其他一些秘密文件或类似的东西可以更具体?
答案 0 :(得分:9)
排序的代码真的太多了吗?
set fso = CreateObject("Scripting.FileSystemObject")
Set outputLines = CreateObject("System.Collections.ArrayList")
for each f in fso.GetFolder(".").files
outputLines.Add f.Name
next
outputLines.Sort() ' 5 lines...
For Each outputLine in outputLines
set file = fso.GetFolder(".").files.item (outputLine&"")
Wscript.Echo file.name ' TODO: your thing here
Next
答案 1 :(得分:7)
如果您想按特定顺序获取文件夹中的文件,则必须自己完成。如果你不喜欢ADO记录集或使用可排序的.NET集合,你可以shell(.Run,.Exec)并处理dir /A:-D /B /O:D /T:C
的输出(没有文件夹,裸格式(没有标题/摘要) ,顺序:日期,时间段:创造)。
<强>更新强>
虽然我确实可以展示.Files集合按名称排序其元素的示例,但盖茨先生明确says:
INFO:FileSystemObject的限制...无法对文件名进行排序 从文件集合 - 您可以遍历File对象 在Files集合中获取文件夹中的文件列表。 但是,File对象未排序。你需要使用一种排序 例程,用于对Files集合中的File对象进行排序。
简单的演示代码,显示:如果要使用shell功能,则需要shell(%comspec%),例如intrinsic commands:
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim goWS : Set goWS = CreateObject("WScript.Shell")
Dim csDir : csDir = "c:\temp"
WScript.Quit demoSF()
Function demoSF()
demoSF = 0
Dim aDSOrd : aDSOrd = getDSOrd(csDir, "%comspec% /c dir /A:-D /B /O:D /T:C """ & csDir & """")
Dim oFile
For Each oFile In aDSOrd
WScript.Echo oFile.DateCreated, oFile.Name
Next
End Function ' demoSF
Function getDSOrd(sDir, sCmd)
Dim dicTmp : Set dicTmp = CreateObject("Scripting.Dictionary")
Dim oExec : Set oExec = goWS.Exec(sCmd)
Do Until oExec.Stdout.AtEndOfStream
dicTmp(goFS.GetFile(goFS.BuildPath(sDir, oExec.Stdout.ReadLine()))) = Empty
Loop
If Not oExec.Stderr.AtEndOfStream Then
WScript.Echo "Error:", oExec.Stderr.ReadAll()
End If
getDSOrd = dicTmp.Keys()
End Function
输出:
cscript 16895525.vbs
07.10.1998 15:31:34 TlbInf32.chm
..
09.10.2008 22:40:29 sqlce.sql
09.10.2008 22:40:29 gltsqlcopytest.sdf
05.11.2008 20:11:39 Vorfuehrung.class
..
28.03.2011 20:23:36 Program.cs
.
01.10.2012 10:10:10 KyXHDe.chm