【问题标题】:Copy the two most recent files to new dir将两个最近的文件复制到新目录
【发布时间】:2013-08-05 19:18:56
【问题描述】:

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

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

谢谢

【问题讨论】:

  • “最近”是什么意思?上次创建还是上次修改?
  • 上次修改。谢谢。

标签: vbscript cmd


【解决方案1】:

在 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 内置的 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

【讨论】:

  • 感谢我选择了 robocopy...ROBOCOPY C:\alohaqs\newdata C:\mirus\schedule *.sch /maxage:15
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 2011-07-12
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
相关资源
最近更新 更多