Generate a Backup File with Timestamp using a Batch Script

In this guide, you’ll see the full steps to create a backup file with a timestamp using a batch script.

Batch Script to Generate a Backup File with Timestamp

Here is the batch script that you can use to generate your backup file:

@echo off

for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set DateTime=%%a

set Yr=%DateTime:~0,4%
set Mon=%DateTime:~4,2%
set Day=%DateTime:~6,2%
set Hr=%DateTime:~8,2%
set Min=%DateTime:~10,2%
set Sec=%DateTime:~12,2%

set BackupName=File Name__%Yr%-%Mon%-%Day%_(%Hr%-%Min%-%Sec%)

copy "Path where your file is stored\File Name.File Type" "Path where your backup file will be stored\%BackupName%.File Type"

You may customize the following parts in the code based on your needs:

BackupName=File Name__%Yr%-%Mon%-%Day%_(%Hr%-%Min%-%Sec%) This is the full file name with the timestamp format (this file name will be created when you execute the batch script). You may change the file name and/or timestamp format
“Path where your file is stored\File Name.File Type” This is the source path where your original file is stored. You’ll have to ensure that the file name specified is identical to the original file name
“Path where your backup file will be stored\%BackupName%.File Type” This represents the target path where your backup file will be stored

Don’t forget to put the file type at the end of the paths (for example, for a CSV file, the file type is “.csv”).

Example with the Steps to Create the Batch Script

Let’s now see the steps to create a batch script to backup a CSV file called ‘Products‘ where the file type is “.csv

(1) First, open Notepad

(2) Then, type/copy the code below into Notepad. You’ll need to modify:

    • The source path to the location where your original file is stored
    • The target path to the location where you want to store the backup file

As mentioned before, don’t forget to add the file type at the end of the paths (here, the CSV file type is “.csv”):

@echo off

for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set DateTime=%%a

set Yr=%DateTime:~0,4%
set Mon=%DateTime:~4,2%
set Day=%DateTime:~6,2%
set Hr=%DateTime:~8,2%
set Min=%DateTime:~10,2%
set Sec=%DateTime:~12,2%

set BackupName=Backup_Products__%Yr%-%Mon%-%Day%_(%Hr%-%Min%-%Sec%)

copy "C:\Users\Ron\Desktop\Test\Products.csv" "C:\Users\Ron\Desktop\Test\%BackupName%.csv"

(3) Save the Notepad with “.bat” extension. Here, let’s save the file as ‘Backup.bat

(4) Once you double-click on the batch file, the backup with the timestamp will be created at your target path.

You may also want to check the following source that contains additional guides about batch scripts.