Batch file to create regular backups with cleanup

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:scriptsbackup.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 %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 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 CREATING FOLDER %BackupTarget%%bkupfldr%\
if not exist "%BackupTarget%%bkupfldr%\" mkdir "%BackupTarget%%bkupfldr%\"

%BackupCmd% "%BackupSource%*.*" "%BackupTarget%%bkupfldr%\"

echo %date% %time%

Hope you will find this useful!

One Reply to “Batch file to create regular backups with cleanup”

  1. I tried this batch file with a slight modification…. first I removed the /s and /e switches from the xcopy as I didn’t want sub folders.

    Next I also changed the “number to keep” variable from 5 to 2 as I only wanted 2 backup at any given moment.

    The batch file ends up making the file copy just fine, however none of the previous backup files are being deleted.

    Any suggestions?

Leave a Reply

Your email address will not be published. Required fields are marked *