Script to Delete Old Files

30 Jul

This is a script I’ve had running for a while, it currently deletes old files from my ftp server when they have been there for 14 days or more. It also checks subfolders.

Set objArgs = WScript.Arguments
FolderName =objArgs(0)
Days=objArgs(1)

set fso = createobject(“scripting.filesystemobject”)
set folders = fso.getfolder(FolderName)
datetoday = now()
newdate = dateadd(“d”, Days*-1, datetoday)
wscript.echo “Today:” & now()
wscript.echo “Started deleting files older than :” & newdate
wscript.echo “________________________________________________”
wscript.echo “”
recurse folders
wscript.echo “”
wscript.echo “Completed deleting files older than :” & newdate
wscript.echo “________________________________________________”

sub recurse( byref folders)
set subfolders = folders.subfolders
set files = folders.files
wscript.echo “”
wscript.echo “Deleting Files under the Folder:” & folders.path
wscript.echo “__________________________________________________________________________”
for each file in files
if file.datelastmodified < newdate then
wscript.echo “Deleting ” & folders.path & “\” & file.name & ” last modified: ” & file.datelastmodified
on error resume next
file.delete
end if

next

for each folder in subfolders
recurse folder
next

set subfolders = nothing
set files = nothing

end sub

Then just call it passing in the directory and the number max file age in number of days.

cscript myscript.vbs c:\files 7

Sorted.

Update:

I should have mentioned, if you are on Windows server, you can use File Server Resource Manager (FSRM) to do this, it’s much neater.