Tuesday, October 28, 2008

formatted date in Windows script

I find the output of the full date command in Windows lacking. Thus, I was trying to find a way to date/time stamp a logfile in a Windows batch script.
C:\WINNT>date /t
Tue 10/28/2008

I only wanted YYYYMMDD_HHmm, where
YYYY = four digit year
MM = two digit day
DD = two digit month
HH = two digit hour
mm = two digit minute

So, I needed to combine outputs from both the Windows date and time functions.

My batch script ended up looking like this:
set dt=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%
bash "siteBackupAll.sh" | tee log%dt%.txt

In the example above, the resulting script outputs a logfile named:
log20081028_1433.txt

The Windows help for SET is pretty cryptic, much like any Unix man page. You can see all the options for Windows shell programming (variables, operators, expressions, etc) if you type
SET /?

at the command prompt.

Variable expansion in Windows is a little weird. Here is a snip from the help, but essentially, you can act on the expansion of a variable (ie, pluck parts from the output) by using a numbering scheme that will start counting from the left or right, depending on whether the number you specify is positive (start from left) or negative (start from right). In essence, the numbering is much like any programmatic substr (substring) function:

May also specify substrings for an expansion. %PATH:~10,5%would expand the PATH environment variable, and then use only the 5characters that begin at the 11th (offset 10) character of the expandedresult. If the length is not specified, then it defaults to theremainder of the variable value. If either number (offset or length) isnegative, then the number used is the length of the environment variablevalue added to the offset or length specified.

%PATH:~-10%would extract the last 10 characters of the PATH variable.
%PATH:~0,-2%would extract all but the last 2 characters of the PATH variable.

'sodo

No comments:

Feel free to drop me a line or ask me a question.