我正在编写一个VBScript,它将删除扩展名为'.bac'的文件超过前10名。 我目前已经编写了代码来删除超过5天的文件,并且只有在文件夹中有超过12个文件但删除了所有旧文件。 我的目标是保留前10个文件扩展名:'。bac',即使它们超过5天,因为它们是我的数据库的备份(一个是配置库的副本,第二个是产品库的副本,所以5文件需要是配置备份,5个文件需要是产品备份。
Option Explicit
On Error Resume Next
Dim oFSO, oFolder, sDirectoryPath
Dim oFileCollection, oFile, sDir
Dim iDaysOld
'Specify Directory Path From Where You want to clear the old files
sDirectoryPath = "D:\Backup"
'Specify Number of Days Old File to Delete
iDaysOld = 5
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sDirectoryPath)
Set oFileCollection = oFolder.Files
'***********************BG File count*************************
Dim strDirectory, nThreshold, counter, extension, msgtext
Dim objFSO, objFolder, objFile, Logfile
'file extension to look for
extension = "bac"
'directory to look in
strDirectory = "D:\Backup"
counter = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDirectory)
For Each objFile In objFolder.Files
If LCase((objFSO.GetExtensionName(objFile))) = LCase(extension) Then
counter = counter + 1
End If
Next
'***********************End of file count*********************
If counter > 12 Then
For each oFile in oFileCollection
'This section will filter the text file as i have used for for test
'Specify the Extension of file that you want to delete
'and the number with Number of character in the file extension
If LCase(Right(Cstr(oFile.Name), 3)) = "bac" Then
If oFile.DateLastModified < (Date() - iDaysOld) Then
oFile.Delete(True)
End If
End If
Next
End If
Set oFSO = Nothing
Set oFolder = Nothing
Set oFileCollection = Nothing
Set oFile = Nothing
答案 0 :(得分:1)
一种方法是编译10个最新文件的列表,例如像这样:
n = 10 'number of files to keep
fldr = "D:\Backup"
ReDim mostRecent(n-1)
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder(fldr).Files
If fso.GetExtensionName(f) = "bac" Then
For i = 0 To n-1
If IsEmpty(mostRecent(i)) Then
Set mostRecent(i) = f
Exit For
ElseIf f.DateLastModified > mostRecent(i).DateLastModified Then
For j = n-2 To i Step -1
If Not IsEmpty(mostRecent(j)) Then Set mostRecent(j+1) = mostRecent(j)
Next
Set mostRecent(i) = f
Exit For
End If
Next
End If
Next
然后删除第二个循环中不在该列表中的所有文件:
'create a lookup table to simplify filename checking
Set lut = CreateObject("Scripting.Dictionary")
For i = 0 To n-1
If Not IsEmpty(mostRecent(i)) Then lut.Add mostRecent(i).Name, True
Next
For Each f in fso.GetFolder(fldr).Files
If Not lut.Exists(f.Name) Then f.Delete
Next
另一种(可能更简单,更快)的方法是shell,在临时文件中使用dir
命令创建目录列表,然后从该临时文件中读取文件列表:
n = 10 'number of files to keep
fldr = "D:\Backup"
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
sh.Run "%COMSPEC% /c dir /a-d /b /o-d /tw """ & fldr & """\*.bac >temp.txt"
Set f = fso.OpenTextFile("temp.txt")
Do Until f.AtEndOfStream
filename = f.ReadLine
If f.Line > n Then fso.DeleteFile fso.BuildPath(fldr, filename)
Loop
f.Close