Thursday, March 16, 2006

VBScript delete files in a folder that are certain days old

Using VBScript to Automate Tasks: "VBScript to delete files in a folder that are certain days old
As part of a disaster recovery plan, you may need to transfer backup files from one server to another. However, you probably don't want to keep accumulating backup files that you run out of space on your backup server. In this case, you want to delete files that are certain days (or weeks) old. The following VBScript can handle this task nicely. You can customize this code, such as changing the value of iDaysOld, to fit your needs. Most of the code should be self-explanatory. For more on disk space management, see one of my articles published a couple of weeks ago.
Option Explicit
on error resume next
Dim oFSO
Dim sDirectoryPath
Dim oFolder
Dim oFileCollection
Dim oFile
Dim iDaysOld

'Customize values here to fit your needs
iDaysOld = 21
Set oFSO = CreateObject("Scripting.FileSystemObject")
sDirectoryPath = "FolderName here. Can be UNC path like \\MyServer\MyFolder"
set oFolder = oFSO.GetFolder(sDirectoryPath)
set oFileCollection = oFolder.Files

'Walk through each file in this folder collection.
'If it is older than 3 weeks (21) days, then delete it.
For each oFile in oFileCollection
If oFile.DateLastModified < (Date() - iDaysOld) Then
oFile.Delete(True)
End If
Next

'Clean up
Set oFSO = Nothing
Set oFolder = Nothing
Set oFileCollection = Nothing
Set oFile = Nothing"

0 Comments:

Post a Comment

<< Home