Deleting files older than a week under Windows

If you’re running a Windows server and want to delete files that are older than, say, a week then Visual Basic comes to the rescue. Once you’ve got the script running you’d like Windows to start it every day so you don’t have to do this manually: at will be your friend here.

The Visual Basic script

For everybody who knows how to program in Visual Basic it’s be pretty easy to write some lines that get the files from a certain directory and deletes them if they haven’t been changed for some time. For everybody else: just copy the following lines into a file e.g. cleaner.vbs.

1
2
3
4
5
6
7
Dim fso, f, f1, fc
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("C:\foo\bar")
Set fc = f.Files
For Each f1 in fc
If DateDiff("d", f1.DateLastModified, Now) > 7 Then f1.Delete
Next

All that’s left to do is to change the folder in line 3 to whatever you want. Have a look at line 6 and adapt the number of days, currently 7, to your needs.

Running the script

The at command helps you to run programs at a certain time. Let’s say we want to run our script every day at 22:30 o’clock (that’s 10:30PM) we would type this on the command prompt:

at 22:30 /every:M,T,W,Th,F,S,Su C:\Scripts\cleaner.vbs

If we just type at we’ll see all the tasks that are planned for execution.

Conclusion

With a simple Visual Basic script and the at command it’s pretty easy to run recurring tasks under Windows. If your Windows server is running longer than a week without rebooting this is a really nice solution.