0

So I have to write a script to delete all files except n newest (most recently created). I'm running my script with two arguments: folder directory and number of files that shouldn't be removed.

Here is my script, but it is actually removing random files. How can I make it to leave n newest files?

How I run script: delete C:\users\Adam\Desktop\Test 3

My script:

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 

Code with sort:

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
murilo
  • 31
  • 1
  • 6

1 Answers1

1

The following should do the job:

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
Gurmanjot Singh
  • 10,224
  • 2
  • 19
  • 43