Friday, November 27, 2009

Name a file based on computer date and time

Problem: we need a Windows batch command file to backup some information into a file and that file must be named based on the date and time of the computer.

Solution:  a script like this should do the required task

rem perform de backup tasks and save the resulting file on a directory, for example e:\backups

rem with a any file name, for example backup.bkf

rem change the current directory to the same where the backup file was created

cd e:\backups

rem proceed to rename using the for function

for /f "tokens=1-6 delims=/: " %%d in ("%date%:%time%") do rename "e:\backups\backup.bkf" ANYTEXT%%d_%%e_%%f_%%g-%%hh%%i.bkf

The command line above can be read as follows:

for the text on %date:%time% split it on tokens taking the characters / or : as delimiters. Use only the tokens 1 to 6 and assign them to letters beginning from d. Finally, rename the file “e:\backups\backup.bkf” with the name formed by the tokens %d,%e,%f%,%g,%h and %i.

The resultant file name can have additional characters. In my example, I am appending the ANYTEXT string to the file name, using the ‘-‘ character to separate date and time on the file name, and including an ‘h’ to separate hour and minutes.

Some examples on the Internet shows the same command but using the tokens 1 to 5. It is important to see how the date and time are actually displayed on the server you are going to run de script in order to choose the right number of tokens. To do that, in a command line you can type date or time and then press ENTER. If the date is not showing the first three letters of the day (for example, Mon for Monday),  you can use the tokens 1 to 5. In my case, my server was showing those three characters before the date and I needed tokens 1 to 6.

Finally, you can run the for command directly on the Windows command line in order to test the rename procedure and being sure that the file is named as you want. However, please take into account that on the command line you don´t need to use the double %% before the token letters. For the command above to be run on the Windows Command line directly, the syntax should be:

for /f "tokens=1-6 delims=/: " %d in ("%date%:%time%") do rename "e:\backups\backup.bkf" ANYTEXT%d_%e_%f_%g-%hh%i.bkf

 

No comments:

Post a Comment