Thursday, August 28, 2008

Batch file to back up a folder and add a timestamp

Last week I needed to write a batch file to copy a directory to another location, but back up the existing target directory first, if it already existed.

I needed a unique name for the backup copy, so that the command could be run repeatedly.

Here it is. Notice the /s and /e parameters on the xcopy command. That's to include the subfolders, including the empty ones:

@echo off
ECHO *********************************************
ECHO * This command will:
ECHO *
ECHO * 1. rename the existing MyFolder directory
ECHO *
ECHO * 2. replace it with a fresh MyFolder.
ECHO *
ECHO *
ECHO * Press Ctrl + C to cancel execution.
ECHO *
ECHO **********************************************

PAUSE

set FileDate=%date:~10,4%_%date:~4,2%_%date:~7,2%
set FileTime=%time:~,2%%time:~3,2%%time:~6,2%%time:~9,2%

rename "C:\Target\MyFolder\" "MyFolder %FileDate% %FileTime%"

xcopy "C:\Source\MyFolder\*.*" /s /e "C:\Target\MyFolder\"

No comments: