【发布时间】:2017-06-28 13:33:54
【问题描述】:
所以我必须编写一个脚本来删除除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
【问题讨论】:
-
当您说“最新”时,您是指最近创建的还是最近修改的?
-
我的意思是创造。
-
如果您想保存最新的文件,您需要在删除除
n之外的所有文件之前对文件进行排序。请参阅this answer 和this answer 了解如何做到这一点。 -
@freginold 的回答中需要用到的属性是 objFile.DateCreated
-
@murilo 解决方案有效吗?