How to generate file name with timestamp in windows batch file?
Recently, we had requirement to generate unique file name to transfer data to another DC in an encrypted format from Windows 2003 server. As a POC and to keep costs down, we decided to use windows batch file scripting to do this. We suffixed data file name with timestamp to make it unique as below
set local
REM Preparing Timestamp Information
set year=%date:~6,4%
set month=%date:~3,2%
set day=%date:~0,2%
set hour=%time:~0,2%
set minute=%time:~3,2%
set seconds=%time:~6,2%
set timestamp=%year%%month%%day%%hour%%minute%%seconds%
set data_file=C:\%timestamp%.txt
However, above script failed to generate file if hour is less than 10 as it returns ‘ 8’ for example with leading space and Windows 2003 rejects file name with space. Fortunately, it is easy to fix by checking hour field and replacing space with 0 as below
set local
REM Preparing Timestamp Information
set year=%date:~6,4%
set month=%date:~3,2%
set day=%date:~0,2%
set hour=%time:~0,2%
REM Replace leading space with zero
if “%hour:~0,1%” ==” ” set hour=0%hour:~1,1%
set minute=%time:~3,2%
set seconds=%time:~6,2%
set timestamp=%year%%month%%day%%hour%%minute%%seconds%
set data_file=C:\%timestamp%.txt