Schedule deleting of files of previous day in a particular folder

Schedule deleting of files of previous day in a particular folder

Although this can be achieved using .bat files i find it very complex.
Hence my approach is to write a vbscript and schedule it to run everyday at
particular time.

//VBScript code

Option Explicit

On Error Resume Next

Dim oFSO, oFolder, sDirectoryPath

Dim oFileCollection, oFile, sDir

Dim iDaysOld

'Specify Directory Path From Where You want to clear the old files

sDirectoryPath = ""

Set oFSO = CreateObject("Scripting.FileSystemObject")

Set oFolder = oFSO.GetFolder(sDirectoryPath)

Set oFileCollection = oFolder.Files

For each oFile in oFileCollection

iDaysOld =datediff("d",oFile.DateLastModified,date())

If iDaysOld>0 Then

oFile.Delete(True)

End If

Next

Set oFSO = Nothing

Set oFolder = Nothing

Set oFileCollection = Nothing

Set oFile = Nothing

Steps to schedule it via schedular in windows 7-

1.Go to Administrative Tools->Task Schedular.

2.create new task.Give it a name in General Tab.

3.In the trigger tab set the schedule it to occur daily at a particular
time.

4.In Action tab give the path where the .vbs is stored.

5.In the settings tab click “Run task as soon as possible after a scheduled
start is missed”.

Commonly encountered problems-

1.What if the system is logged of for days ..

Solution: Either active the notication facility in task schedular and
delete the files manually or

Create one more task indicating that the .vbs should run whenver the user
logs into the system.

2.what if the user has stord some files today in that path and logged
of...when he logs in again wouldnt that folders get deleted—

Solution: No the code is such that it will delete only files from previous
days.So even if schdule is missed the second task will delete the files.

2 comments: