Monday, October 18, 2010

Append a date to a filename issue (DOS Command)

Say,
-%DATE:~8,2%-%DATE:~0,2%-%DATE:~3,2%

7z a -xr!*.tmp C:\backupfiles_%date:/=%.zip D:\backupfiles\
You will get the file name correctly as ==> backupfiles_08152008.zip
However, sometime the file name became ==> backupfile_Fri.7z

The reason for the difference is that the scheduled task is running under a different user account than the one you are using when you open the command prompt and it's regional settings are different.
The format of the %date% variable depends on the regional settings. For example, under English (United States) it will be Sat 08/16/2008 and under English (Caribbean) it will be just 08/16/2008.
The space after the day of the week is the problem. Your command line will look like this:

7z a -xr!*.tmp C:\backupfiles_Sat 08162008.zip D:\backupfiles\

It sees the archive name as C:\backupfiles_Sat and adds the default .7z extension creating an archive named C:\backupfiles_Sat.7z. It sees 08162008.zip and D:\backupfiles\ as the files to add, and most likely gives an error that it can't find 08162008.zip, though it should add all of the files from D:\backupfiles\. You might not see the error when running as a scheduled job as the window closes too fast.

Because of the space you must put the archive name in quotes:
7z a -xr!*.tmp "C:\backupfiles_%date:/=%.zip" D:\backupfiles\
This will create a file named C:\backupfiles_Sat 08162008.zip.

If you don't want the day of the week, you can either log into the account you run the scheduled tasks under and change the regional settings, or use a variable and then specify a substring to extract just the date portion like this:
Code:

set _d=%date:/=%
7z a -xr!*.tmp C:\backupfiles_%_d:~4%.zip D:\backupfiles\
set _d=

No comments: