Windows batch file - calculating filename from current date
I would like to create an environment variable to hold a filename something like:
PREFIX-2010-AUG-09.zip
I can get close if I use something like this:
SET filename=PREFIX-%date:~-4,4%-%date:~-7,2%-%date:~0,2%.zip
Result:
PREFIX-2010-08-09.zip
but in this case, I get the month as two digits (08).
Is there any easy trick in Windows batch files to get the three-letter month abbrevia开发者_运维技巧tion from the numeric month (e.g. 08 for "AUG" = August) ??
Update: this needs to be run on a Windows 2008 R2 Server, and yes, if someone can show me a PowerShell solution, that would work, too :-) Thanks!
This is something like a look up table:
set month_01=JAN
set month_02=FEB
set month_03=MAR
@rem ...
set number=02
for %%a in (month_%number%) do call set month_as_text=%%%%a%%
echo %month_as_text%
The value in %number%
in the for
loop is used to dereference the matching variable name.
Or even shorter:
set number=02
for /f "tokens=%number%" %%m in ("JAN FEB MAR APR ...") do set month_as_text=%m
echo %month_as_text%
EDIT:
Johannes suggests a shorthand for the 1st version:
set month_01=JAN
set month_02=FEB
set month_03=MAR
@rem ...
set number=02
setlocal enabledelayedexpansion
set month_as_text=!month_%number%!
echo %month_as_text%
You could always do the number-to-text translation by hand, like:
if %MM%==01 set MM=Jan
if %MM%==02 set MM=Feb
if %MM%==03 set MM=Mar
if %MM%==04 set MM=Apr
etc.
The first answer is incorrect for August and September. The reason is that the shell interprets a leading zero as octal, and 08 and 09 are not valid octal numbers. You can see this easily for yourself by running this command:
for /f "tokens=08" %a in ("A B C D E F G H I J") do echo %a
If you replace the 08
above with 09
it will also fail. It will work if you use 07
or 10
. A working implementation is as follows:
months=JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
:: get the month as a 2-digit number
set number=%date:~4,2%
:: remove leading zero
for /f "tokens=* delims=0" %%a in ("%number%") do set number=%%a
:: index into array to get month name
for /f "tokens=%number%" %%m in ("%months%") do set month_as_text=%%m
:: print month name
echo %month_as_text%
精彩评论