0

VBScript または .bat ファイルを作成して、ディレクトリ a にある特定の拡張子の最新の 2 つのファイルを*.sch別のディレクトリに移動したいと考えています。

2番目に新しいものを見つけるには$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 組み込み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
于 2013-08-05T20:42:06.327 に答える