StevensNet.com

...Because someone's gotta tell the story...

Blogs

To return to the main Blog List, click Full Blog Listing.

Tags

Error
SQL
Technical
Troubleshoot
VBScript

VBScript: Deleting all files older than (xx) days

Thursday, March 20, 2008 in Technical Articles (Views: 4462)
Quickie blog on a helpful topic - how to clean your disk of old backup or temp files.

This is a script I threw together in VBScript to delete old SQL backup jobs (since SQL Server 2005 no longer supports deleting old database backups as part of a maintenance plan).

This script looks in a folder, enumerates the files, and deletes any file older than a specified amount of days (from the commmand line). This will delete all files, not a wild card such as *.bak or *.tmp.

Hope you find this useful...

'Delete files older than (xx) days
'Syntax: cscript deloldfiles.vbs (path) (number of days)
'Example: cscript deloldfiles.vbs c:\temp 10
'Deletes files 10 days old (or older) in c:\temp

on error resume next

Set objArgs = WScript.Arguments
FolderName =objArgs(0)
Days=objArgs(1)
if foldername="" then
wscript.echo "Incorrect Syntax."
wscript.quit
end if

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

 

Related Blogs You May Be Interested In:


To leave a comment, please log in and/or register.