≡ Menu

Create unique named file from batch script

This post explains how to create files with unique names from batch files.  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 there’s no conflict with the previously created files.

One commonly used technique for unique names is to append the system time to the names. Let’s see how we can implement this in a Windows batch file.

To create a unique file with just 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

c:\>dir
11/15/2015  07:35 PM             2,288 11-15-2015.txt

To create unique file 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 timestamp 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.

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

Creating directory with unique 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
11-15-2015
2 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%
    20948

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

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

    • Srini

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

Leave a Comment