This article introduces a method to delete old backup or log files from folders in order to prevent waste of disk space.
As a system administrator, you may want to check the folders which contain backup or log files. Any backup method you are using generates several files, for example, daily files. If you don't clear these folders from time to time, it will fill up your disk space after some time.
There should be an effective way to delete old files automatically. Some platforms like Linux offer the Log Rotation daemon which automatically removes files at certain times and deletes old files. Since in Windows there is no specific way to do this, you should modify your scripts to generate separate backup or log files, and use the script I'm going to present here to keep a certain number of new files and delete the older files.
Using the Code
Suppose you have a folder containing multiple files and you want to keep, for example, the four newest files and delete the others.
If the folder contains these files:
The script reads the last modified date of the files and sorts them and deletes the older files:
For this purpose, put this VBScript code somewhere in your hard drive and create a batch file in the same folder as the script, which runs this script. You need to run the batch file automatically using Windows Scheduled Task.
Path = WScript.Arguments.Item(0)
Set fs = WScript.CreateObject ("Scripting.FileSystemObject")
Set ContentFolder = fs.GetFolder(Path)
Set Files = ContentFolder.Files
Count = Files.Count
For Each File in Files
FileName = File.Name
ModifiedDate = File.DateLastModified
FileNames(i) = FileName
ModifiedDates(i) = ModifiedDate
For i=0 to Count-1
For j=0 to i-1
If ModifiedDates(i) > ModifiedDates(j) Then
TempDate = ModifiedDates(i)
TempName = FileNames(i)
ModifiedDates(i) = ModifiedDates(j)
FileNames(i) = FileNames(j)
ModifiedDates(j) = TempDate
FileNames(j) = TempName
For i=MaxFiles to Count-1
FullPath= Path & "\\" & FileNames(i)
The batch file will run periodically to delete the old files in the your folders.
The first command keeps the five newest files in Your_Folder_1, and the second command keeps the seven newest files and delete the old ones.
wscript Rotator.vbs Your_Folder_1 5
wscript Rotator.vbs Your_Folder_2 7
Points of Interest
Actually, it was a bad idea to delete the files older than, for example, seven days. Because if your backup method scripts fail to run for seven days and the Rotator script ran everyday, you would face an empty folder after seven days, which is not desirable.
Instead, the idea of keeping the seven new files is not risky even if the backup methods fail. So after seven days, at least you will have the old backups intact, and you will not be blamed for destroying data. So running this script is completely safe.