Wednesday, March 18, 2009

all-purpose vbs backup script

a simple vbs script that make a daily, weekly and monthly copy of a folder. It maintains 7 days worth of backups.
here's the code:

Dim oFS, backup_dir_w, backup_dir_m, backup_dir_d, backup_sorg
Dim timedir, timedir_del, date_7

'# SET YOUR PATHS HERE ####
backup_sorg = "C:\source_folder"
backup_dir_d = "C:\destination_folder\Daily\"
backup_dir_w = "C:\destination_folder\Weekly\"
backup_dir_m = "C:\destination_folder\Monthly\"

if right(backup_sorg, 1) = "\" then
backup_sorg = Left(backup_sorg, (Len(backup_sorg) - 1))
end if
if right(backup_dir_d, 1) <> "\" then
backup_dir_d = backup_dir_d & "\"
end if
if right(backup_dir_w, 1) <> "\" then
backup_dir_w = backup_dir_w & "\"
end if
if right(backup_dir_m, 1) <> "\" then
backup_dir_m = backup_dir_m & "\"
end if

Set oFS = CreateObject("Scripting.FileSystemObject")

'##### DAILY BACKUP FOLDER ####
timedir = backup_dir_d & Year(Date) & PadZero(Month(Date)) & PadZero(Day(Date)) & "\"
oFS.CreateFolder(timedir)

'#### DAILY FOLDER ####

oFS.CopyFolder backup_sorg, timedir

'#### DELETE 7 DAYS OLD BACKUP ####
date_7 = (DateAdd("d",-7,now()))
timedir_del = backup_dir_d & Year(date_7) & PadZero(Month(date_7)) & PadZero(Day(date_7))

If oFS.FolderExists(timedir_del & "\") Then
oFS.DeleteFolder timedir_del
End If
'################################

timedir = Left(timedir, (Len(timedir) - 1))

'#### WEEKLY BACKUP ####
if WeekDay(Now()) = 6 then
oFS.CopyFolder timedir, backup_dir_w
end if

'#### MONTHLY BACKUP ####
if Day(Now()) = 1 then
oFS.CopyFolder timedir, backup_dir_m
end if
'########################

Set oFS = Nothing

' PadZero - add 0 if value min 10
Function PadZero(val)

If (val < 10) Then
PadZero = "0" & val
Else
PadZero = val
End If

End Function

No comments: