How to remove files from folder with VBScript

Here is the script. It is usefull for example if you need to remove old backup files from a folder or some old log files. The only thing is to put it to task schedule. Here is the script:

Dim Fso

Dim Directory

Dim Modified

Dim Files

Set Fso = CreateObject(“Scripting.FileSystemObject”)

Set Directory = Fso.GetFolder(“C:\inetpub\logs\logfiles\W3SVC3”)

Set Files = Directory.Files

For Each Modified in Files

If DateDiff(“D”, Modified.DateLastModified, Now) > 30 Then Modified.Delete

Next

So some explanations

Set Fso = CreateObject(“Scripting.FileSystemObject”) //create file system objct

Set Directory = Fso.GetFolder(“some path”) //this is the actual folder which will be searched for files

For Each Modified in Files //this is the actual loop for every file in the directory

If DateDiff(“D”, Modified.DateLastModified, Now) > 30 Then Modified.Delete //here you should set how log the files will be keeped. 30 in this example means if  the files is more than 30 days old then delete it. The funktion compares every file with today date and in this cause if today is 30 days more than date of some file it deletes it.

After that make a simple task schedule with cscript <some filename.vbs>. This will run script in command line.

Here there is some slightly different modification of the script. If somebody wonders how the script could be modified in that manner, that it can remove old files (or data) from subfolder beneath some root folder. Here is the modified script.

Let’s say we have the followind scenario. We have Microsoft SQL server 2008 and a maintenance plan which takes care of backups. All backups have been made in a folder called D:\SQL Backups.

In addition to the above script i will introduce a variable  Dim Subdirectory. In that cause we have Directory and Subdirectory variables. The difference is the line Set SubDirectory = Directory.Subfolders. Whith that line Subdirectory variable gets all subdirectories underneath. f1 is some kind of subsidiary variable represent object to access to every file in every subdirectory.

Dim Fso

Dim Directory

Dim Modified

Dim Files

Dim SubDirectory

Dim f1

Set Fso = CreateObject(“Scripting.FileSystemObject”)

Set Directory = Fso.GetFolder(“D:\SQL Backups”)

Set SubDirectory = Directory.Subfolders

For Each f1 in Subdirectory

Set Files = f1.Files

For Each Modified in Files

If DateDiff(“D”, Modified.DateLastModified, Now) > 3 Then Modified.Delete

Next

Next

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: