Tuesday, July 29, 2008

Getting formatted date into variable in batch file

There are many times I create a batch file to do backups of a deployment before I do a new deployment. I want to keep the history of deployment backups, so I want to include the current date and time in the filename. I could not believe how incredibly different and complex the solutions were for this when I Googled it. I am doing this on my own machine or at least environments that I know so this batch file doesn't have to worry about this working on all machines with different date formats, etc. The script can be adjusted to work on any date format, but it will not work as is on all date formats. As it turns outs there is already a variable with the date and another with time in it called %date% and %time%. You can see this by typing echo %date% %time% at a command prompt. On my machine this returns a string like the following: Tue 07/29/2008 11:30:10.54 A little know bit of functionality built into the command prompt (at least in XP and maybe earlier) is substring functionality. It uses zero based indexes. Using the previous example we can reformat the output to be just about anything we want. As an example lets do 2008-07-29--11.30. To do this we would do the following echo %date:~10,4%-%date:~4,2%-%date:~7,2%--%time:~0,2%.%time:~3,2% Now if you want to use this in a script that zips a directory and gives the filename with the current date and time here is what you could do: set NOW=%date:~10,4%-%date:~4,2%-%date:~7,2%--%time:~0,2%.%time:~3,2% zip -r c:\myApp%NOW%BU.zip \\myserver\myapp

10 comments:

AdriaNnLA said...

thanks for this -- great tip -- in implementing I discovered one problem, that is the hour in time will not be zero padded (for those less than ten) but is padded with a space -- this causes problems

the solution is to extract and fix (remove the space (if any) and pad with zero, then from that extract just the last two digits in case we now have a three digit number) the hour from time then use that in our new NOW statement:

set /a UHH=%TIME:~0,2%
set OHH=0%UHH%
set HH=%OHH:~-2%
SET NOW=%date:~10,4%-%date:~4,2%-%date:~7,2%--%HH%.%time:~3,2%

Brent V said...

AdriaNnLA,

That is awesome! Thank you for the fix. I had not had a chance to fix it since I noticed the same bug. Thank you very much.

Abhijit said...

Hi geek,
Thank you for the post it was very useful. Keep the good work going.

Regards,
Abhijit

Abhijit said...

In the last line of code zip -r c:\myApp%NOW%BU.zip \\myserver\myapp,
% is missing after BU :)

Stefan Rådström said...

AdriaNnLA's tips works, but a shorter way to convert the leading space of %TIME% for a hour between 00 to 09 is:

set TIMETMP=%TIME: =0%

Then just use TIMETMP instead of TIME.

Anonymous said...

Anyone have an idea????????

THIS WORKS....

set mm=%date:~4,2%
set dd=%date:~7,2%
set yyyy=%date:~10,4%
echo %mm%-%dd%-%yyyy%

xcopy o:\archive\2*.txt e:\tobeexported\jda\MediLinksWork\ /D:04-29-2011


THIS DOES NOT WORK???

set mm=%date:~4,2%
set dd=%date:~7,2%
set yyyy=%date:~10,4%
echo %mm%-%dd%-%yyyy%

xcopy o:\archive\2*.txt e:\tobeexported\jda\MediLinksWork\ /D:%mm%-%dd%-%yyyy%

poly said...

for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set year=%%c
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set month=%%a
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set day=%%b

echo The Year is %year%
echo The Month is %month%
echo The Day is %day%

REM now lets make a directory with the date in it

md C:\%year%.%month%.%day%

cd C:\2011.05.29

bgrupczy said...

Should take rollover into account. Grab the date and time at the start and use those throughout the file.

@set mydate=%date%
@set mytime=%time%
@set CurrentDate=%mydate:~-4,4%%mydate:~-7,2%%mydate:~-10,2%
@set /a hr=%mytime:~0,2%
@set hr=0%hr%
@set hr=%hr:~-2%
@set CurrentTime=%hr%%mytime:~-8,2%%mytime:~-5,2%
@set TimeStamp=%CurrentDate%_%CurrentTime%

Anonymous said...

Thanks to all. This is very helpful.

Anonymous said...

**:: The following is Copyright © 2012 ShopNetNuke Corp. All rights reserved.
:: and released under the GNU General Public License (GPLv3)**

:: The following section retrieves the current date and time and formats it into the '%var%' variable
:: This format always ensures that the Date and Time are fixed length to avoid the situation of
:: having a value of '12/ 1/2012 rather than '12/01/2012'
echo off
for /f "tokens=1-5 delims=:" %%d in ("%time%") do set var=%date:~10,4%-%date:~4,2%-%date:~7,2%-%%d-%%e
set var=%var: =0%
echo Beginning my valuable Backup Set: Backup--%var%
echo Starting SQL Server Database Backup Job...
:: The following line initiates the Backup job within SqlServer Agent.
:: Change 'MyBackupNameInSqlAgent' to the name of the job you want executed
:: Change the directory paths to those relevant to your current system installation directories
"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd.exe" -S SQLSERVERNAME\INSTANCENAME -Q "execute msdb.dbo.sp_start_job @job_name = 'MyBackupNameInSqlAgent'"
:: An error will be returned if the Backup job is not found or has already been triggered by another process

echo Starting My Valuable Source Code Directory Backup...
echo ...backing up files and folders in "C:\Source\MyPreciousProjectDirectory\"...
:: The following line will execute the 7zip command to create a .7z file of the directory named in 'MyPreciousProjectDirectory'
:: and tells it to put the archive in the 'MyPreciousBackupDirectory'. The compression level will be defined by the 7zip default settings
:: The -p flag tells 7zip to password protect the archive, in this case, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectory\%var%\MyPreciousProject--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\*

echo Source Code Directory Backups complete.
echo Archiving Database Backups now...
:: The following line will execute the 7zip command to archive the Database backup.
:: The '*' could be replaced by the actual backup name.
:: The '*' indicates all files of type '.bak'
:: The -p flag tells 7zip to password protect the archive, in this case, again, I've used the Date/Time portion of the filename as the password
:: remove the '-p%var%' section to remove password protection from the archive
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectory\%var%\MyPreciousProject-Database-%var%.7z -p%var% -mhe "C:\Program Files\Microsoft SQL Server\MSSQL10.SQLDEV08\MSSQL\Backup\*.bak"

echo Database Backup Archival process complete.
:: If you wanted to place both the previous backups into one single combination archive,
:: you could do something like the following
"C:\Program Files\7-Zip\7z.exe" a -t7z C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var%\MyPreciousProjectBackupSourceAndDatabase--%var%.7z -p%var% -mhe C:\Source\MyPreciousProjectDirectory\*

echo Now attempting to copy archives to Network Server...
:: The following line will use xcopy to copy the arechives to the server backup directory and place them in a directory named by the DateTime variable %var%
xcopy /S /I /J /Y C:\MyPreciousBackupDirectory\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%
:: Or if the combination above was used then copy that...
xcopy /S /I /J /Y C:\MyPreciousBackupDirectoryForSourceAndDatabase\%var% \\MyPreciousBackupServerName\SourceCode\MyPreciousServerBackupDirectory\%var%