Windows backup bat script using xcopy

Recently I had the need to create a bat script that could be executed by the Windows Scheduled Tasks. The purpose was to copy files from one server to another as a cheap way to backup files created by MSSQL backing up the databases. Here is the .bat file contents (cleaned up to protect sensitive data):

@echo
:: variables
set sourcedrive=D:\
set backupdrive=\\servername\d$
set backupcmd=xcopy /s /c /d /e /h /i /r /y
 
echo # # # Moving files
%backupcmd% "%sourcedrive%\directory_to_backup" "%backupdrive%\directory_to_store_backup"
 
echo # # Moveing Complete!

(NOTE: I am doing this backup via an internal network and using a user account that exists on both systems. Security may dictate that you handle this differently based on your circumstances.)

Notice that for the backupdrive I am calling another Windows server and using the d$. This would require that the Windows Scheduled Task be executed using a user that is trusted on both machines. Also you could specify a local directory on the same server if you did not need to copy the files to another server.

If I were executing this via Window Scheduled Tasks there is nowhere for me to see what happened, what files were moved, etc. This can be solved by adding the following line in the variables area specifying a log file to capture all output that would normally be seen via command line:

set logfile=D:\backup_log_file.txt

Then I would append “>> %logfile%” to the end of each line so that it would be added to the log file. In addition I could prepend “%Date%” after echo on each line to date stamp each line.

Here is what the final file with these two additions would look like:

@echo
:: variables
set sourcedrive=D:\
set backupdrive=\\servername\d$
set backupcmd=xcopy /s /c /d /e /h /i /r /y
set logfile=D:\backup_log_file.txt
 
echo %Date% # # # Moving files >> %logfile%
%backupcmd% "%sourcedrive%\directory_to_backup" "%backupdrive%\directory_to_store_backup" >> %logfile%
 
echo %Date% # # Moveing Complete! >> %logfile%

Published by

Adam

Application Architect from Florida

2 thoughts on “Windows backup bat script using xcopy”

Leave a Reply

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