删除除少数以外的所有文件

时间:2017-06-28 13:33:54

标签: file-io vbscript

所以我必须编写一个脚本来删除除n最新(最近创建的)之外的所有文件。我正在使用两个参数运行我的脚本:文件夹目录和不应删除的文件数。

这是我的脚本,但它实际上是删除随机文件。如何让它留下n个最新文件?

我如何运行脚本:delete C:\users\Adam\Desktop\Test 3

我的剧本:

Dim address
Dim n
Set fso = CreateObject("Scripting.FileSystemObject")

If (Wscript.Arguments.Count <> 2) Then
    MsgBox("Wrong number of paramets")
Else
    address = Wscript.Arguments(0)
    n = Wscript.Arguments(1)
    MsgBox( address & " " & n)
    Set objFolder = fso.GetFolder(address)
    For Each objFile in objFolder.files
        If n <> 0 Then
            n = n - 1
        else
            objFile.Delete True
        End If
    Next
End if 

排序代码:

Function SortFiles(files)
  ReDim sorted(files.Count - 1)
  Dim file, i, j
  i = 0
  For Each file in files 
    Set sorted(i) = file
    i = i + 1
  Next
  For i = 0 to files.Count - 2 
    For j = i + 1 to files.Count - 1
      If sorted(i).DateLastModified < sorted(j).DateLastModified Then
        Dim tmp
        Set tmp = sorted(i)
        Set sorted(i) = sorted(j)
        Set sorted(j) = tmp
     End If
    Next
  Next
  SortFiles = sorted
End Function

If (Wscript.Arguments.Count <> 2) Then
    MsgBox("Wrong number of paramets")
else
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim files
    address = Wscript.Arguments(0)
    n = Wscript.Arguments(1)
    Set files = fso.GetFolder(address).Files
    Dim file
    For Each file in SortFiles(files)
        If n <> 0 Then
            n = n - 1
        else
            file.Delete True
        End If
    Next
end if

1 个答案:

答案 0 :(得分:1)

以下应该做的工作:

Dim address
Dim n, no_of_files

Set fso = CreateObject("Scripting.FileSystemObject")

If (Wscript.Arguments.Count <> 2) Then
    MsgBox("Wrong number of paramets")
Else
    address = Wscript.Arguments(0)
    n = Wscript.Arguments(1)
    MsgBox( address & " " & n)
    Set objFol = fso.GetFolder(path)
    no_of_files = n
    While no_of_files>0
        latestDate = 0
        Set objFiles = objFol.Files

        'Loop to get the creation date of the newest File 
        For Each file In objFiles
            tempDate = file.DateCreated
            If CDate(tempDate)>CDate(latestDate) Then
                latestDate = tempDate
            End If
        Next

        'Loop to delete the newest file using the date fetched in the last loop
        For Each file In objFiles
            If file.DateCreated = latestDate Then
                file.Delete True
            End If
        Next
        no_of_files = no_of_files-1
    Wend
End if
Set fso = Nothing