Search the Site

Sponsors

bottom corner

Batch file to create regular backups with cleanup

This article provides a sample Windows batch file to back up a file directory to a specified location, with a feature to clean up older backup sets.

This page is filed under keyword(s): windows.

I run a version of the Windows batch script below to create a regular backup of one of the folders that contains my daily work; for this illustration, we will call the source folder c:\source\. Every night, this batch file is triggered by Windows Scheduled Tasks to create a folder in my backup drive with the timestamp in the folder name; let us call this target folder D:\target\. Before creating this daily backup, the script also checks to see how many backup sets are already existing in the backup folder, and if above the threshhold, the oldest one(s) are deleted; this feature helps making sure the space usage of redundant backup sets do not get out of control. When scheduling this job with Windows Scheduled Tasks, you may wish to output to a file as well to create a log file of what old folders were removed and what files were copied (eg. "c:\scripts\backup.bat > logfile.log").

@echo off

:: Start Variables

set NumberToKeep=5
set BackupCmd=xcopy /s /c /d /e /h /i /r /y

set BackupSource=C:\source\
set BackupTarget=D:\target\

:: End Variables




:: Actual Script Starts Here!
echo+
echo STARTING BACKUP
echo %date% %time%

:: 1. Delete older backup set(s) beyond the NumberToKeep
for /F "tokens=* skip=%NumberToKeep%" %%I In ('dir "%BackupTarget%" /AD /B /O-D /TW') do (
	echo+
	echo DELETING OLD BACKUP SET %BackupTarget%%%~I
	rd /s /q "%BackupTarget%%%~I"
)

:: 2. Create new backup set
set bkuphour=%time:~0,2%
if "%bkuphour:~0,1%"==" " set bkuphour=0%time:~1,1%
set bkupfldr=%date:~10,4%_%date:~4,2%_%date:~7,2%_%bkuphour%_%time:~3,2%

echo+
echo CREATING FOLDER %BackupTarget%%bkupfldr%\
if not exist "%BackupTarget%%bkupfldr%\" mkdir "%BackupTarget%%bkupfldr%\"

echo+
echo BACKING UP FILES...
%BackupCmd% "%BackupSource%*.*" "%BackupTarget%%bkupfldr%\"

echo+
echo BACKUP COMPLETED!
echo %date% %time%

Hope you will find this useful!

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): windows.
Author: C. Peter Chen
Last updated: 1 Aug 2012

bottom corner