Generate unique file name with timestamp in batch script

Viewed 79608

In my .bat file I want to generate a unique name for files/directories based on date-time.

e.g.

Build-2009-10-29-10-59-00

The problem is that %TIME% won't do because it contains characters that are illegal in filename (e.g. :).

Is there something like tr in batch files?

Any other ideas how to solve this (that don't require extra command line utilities aside from the batch interpreter)?

8 Answers

I use this to create a unique file name for the execution of the batch file.

REM ****Set up Logging ****
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
set mytime=%mytime: =0%

set Logname="PCCU_%mydate%_%mytime%.log"
Echo.  >>%Logname% 2>>&1
Echo.=================== >>%Logname% 2>>&1

I had to add the line

set mytime=%mytime: =0%

because I had the same problem where a blank was being entered before 10 AM, now I get 09 instead of 9. I also reuse the %mydate% and %mytime% variable for other files that I create with this script so that they all have the same date time stamp.

I made this universal, Will work on any environment where date format may be different.

echo off
if not exist "C:\SWLOG\" mkdir C:\SWLOG
cd C:\SWLOG\
cmd /c "powershell get-date -format ^"{yyyyMMdd-HHmmss}^""> result.txt
REM echo %time% > result.txt
type result.txt > result1.txt
set /p filename=<result1.txt
echo %filename%
del C:\SWLOG\result.txt
del C:\SWLOG\result1.txt

Datetime stamp:

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
rem set "datestamp=%YY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "datestamp=%YYYY%%MM%%DD%" 
set "timestamp=%HH%%Min%%Sec%"
set unique_number=%datestamp%%timestamp%
echo %unique_number%
Related