Copy the two most recent files to new dir

2019-09-02 18:36发布

I would like to write a VBScript or .bat file to move the two most recent files of a specific extension *.sch in directory a to a different directory.

I have experimented with $newest How do I find second newest?

Thanks

标签: vbscript cmd
1条回答
孤傲高冷的网名
2楼-- · 2019-09-02 19:34

In VBScript you could do it like this:

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

Edit: The above code isn't too extensible, though. If you need more than just the most recent 2 files you may want to take a slightly different approach. Create an array the size of the number of files you want to handle, and do a sorted insert as long as you have free slots or the current file is newer than the oldest file already in the array.

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

An alternative would be shelling out to the CMD-builtin dir command and reading its output:

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
查看更多
登录 后发表回答