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.
1 2 3 4 5 6 7
Dim fso, f, f1, fc Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.GetFolder("C:foobar") 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
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:Scriptscleaner.vbs
If we just type
at we’ll see all the tasks that are planned for execution.
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.
5 thoughts on “Deleting files older than a week under Windows”
Excellent little script. works a treat and is in use right now for me.
I have one question for you. Does this script delete files to the recycle bin or permanently?
glad you like the script. Right now it deletes files permanently, i.e. you can’t restore them from the recycle bin. Just make sure you’ve inserted the correct directory with the files you really want to delete 😉
That is perfect, I would rather skip the recycle bin. But for future reference, is there a command to delete to the recycle bin?
in fact I know just the basics of VBS and can’t say how you would delete files to the recycle bin first. Sorry.
No worries. Your script is handy and in use, I will do some more research and see what I come up with.
Comments are closed.