0

我想编写一个 VBScript 或 .bat 文件来将*.sch目录 a 中特定扩展名的两个最新文件移动到不同的目录。

我已经尝试过$newest如何找到第二个最新的?

谢谢

4

1 回答 1

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

另一种方法是使用 CMD-builtindir命令并读取其输出:

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
于 2013-08-05T20:42:06.327 回答