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