我想编写一个VBScript或.bat文件,将目录a中特定扩展名*.sch
的两个最新文件移动到另一个目录。
我已尝试$newest
如何找到第二个最新版本?
由于
答案 0 :(得分:2)
在VBScript中你可以这样做:
src = "C:\source\folder"
dst = "C:\destination\folder"
Set fso = CreateObject("Scripting.FileSystemObject")
mostRecent = Array(Nothing, Nothing)
For Each f In fso.GetFolder(src).Files
If LCase(fso.GetExtensionName(f.Name)) = "sch" Then
If mostRecent(0) Is Nothing Then
Set mostRecent(0) = f
ElseIf f.DateLastModified > mostRecent(0).DateLastModified Then
Set mostRecent(1) = mostRecent(0)
Set mostRecent(0) = f
ElseIf mostRecent(1) Is Nothing Or f.DateLastModified > mostRecent(1).DateLastModified Then
Set mostRecent(1) = f
End If
End If
Next
For i = 0 To 1
If Not mostRecent(i) Is Nothing Then mostRecent(i).Copy dst & "\"
Next
编辑:但上述代码不太可扩展。如果您需要的不仅仅是最新的2个文件,您可能需要采取稍微不同的方法。创建一个数组,其大小与您要处理的文件数量相同,只要您有空闲插槽或当前文件比数组中已有的最旧文件更新,就可以执行排序插入。
src = "C:\source\folder"
dst = "C:\destination\folder"
num = 2
last = num-1
Function IsNewer(a, b)
IsNewer = False
If b Is Nothing Then
IsNewer = True
Exit Function
End If
If a.DateLastModified > b.DateLastModified Then IsNewer = True
End Function
Set fso = CreateObject("Scripting.FileSystemObject")
ReDim mostRecent(last)
For i = 0 To last
Set mostRecent(i) = Nothing
Next
For Each f In fso.GetFolder(src).Files
If LCase(fso.GetExtensionName(f.Name)) = "sch" Then
If IsNewer(f, mostRecent(last)) Then Set mostRecent(last) = Nothing
For i = last To 1 Step -1
If Not IsNewer(f, mostRecent(i-1)) Then Exit For
If Not mostRecent(i-1) Is Nothing Then
Set mostRecent(i) = mostRecent(i-1)
Set mostRecent(i-1) = Nothing
End If
Next
If mostRecent(i) Is Nothing Then Set mostRecent(i) = f
End If
Next
For i = 0 To num-1
If Not mostRecent(i) Is Nothing Then mostRecent(i).Copy dst & "\"
Next
另一种方法是shell-out到CMD-builtin dir
命令并读取其输出:
num = 2
Set fso = CreateObject("Scripting.FileSystemObject")
Set sh = CreateObject("WScript.Shell")
cmd = "cmd /c dir /a-d /b /o-d """ & sh.CurrentDirectory & """\*.*"
Set dir = sh.Exec(cmd)
Do While dir.Status = 0
WScript.Sleep 100
Loop
i = num
Do Until i = 0 Or dir.StdOut.AtEndOfStream
f = dir.StdOut.ReadLine
fso.CopyFile f, dst & "\"
i = i - 1
Loop