≡ Menu

Create unique file name from batch script

This post explains how to create unique file names from batch script.  We would need this when we are running some script which writes data into files and each time you need to name the file uniquely so that it does not overwrite previously created files.

One commonly used technique for unique file names is to append the system time to the names. Below are some examples to implement this in a Windows batch script.

To create a unique file name with date

This is helpful if the file is created just once per day.
Example: Let’s say you need to run dir and save the output in a file every day.

@echo off
for /F "tokens=2" %%i in ('date /t') do set mydate=%%i
set filename=%mydate:/=-%.txt
dir > %filename%

After running the above command, a new file gets created with today’s date

11/15/2015  07:35 PM             2,288 11-15-2015.txt

To create unique file name with date and time

If you need to run the script multiple times in a day, just using the date would not be enough. Adding time stamp to the file name ensures that the file name is always unique.

@echo off
for /F "tokens=2" %%i in ('date /t') do set mydate=%%i
set mydate=%mydate:/=-%
set mytime=%time::=-%
set filename=%mydate%-%mytime%.txt
dir > %filename%

After running the batch file, you would see new file created with date and time in the name.

11/15/2015  07:44 PM             2,487 11-15-2015-19-44-38.48.txt

Create unique directory name using date

@echo off
for /F "tokens=2" %%i in ('date /t') do set mydate=%%i
set dirname=%mydate:/=-%.txt
mkdir dirname

After running the batch script, printing all directories in the folder shows the newly created folder with date in the name

c:\> dir /A:D /b
3 comments… add one
  • Pete Wood

    I’ve used the %random% environment variable to achieve a similar effect in the past. I believe it is limited to five digits.

    C:\Users\pwood>echo %random%
    C:\Users\pwood>echo %random%

    Thanks for your support for the command line, it is appreciated.

    • Srini

      That’s a good idea. Thanks Wood for sharing it.

  • Mark


    Maybe I’m wrong, but to run the second example (create unique file with date and time) I had to change

    set mydate=%mydate:/=-%
    set mydate=%date:/=-%

Leave a Comment