A little while back, I wrote this tip on DOS Batch File Date Tips for Windows 7 and Server 2008. I was asked for a clarification for XP as well (due to the minor differences), so I’m writing this as an alternate version of the same previous post.
No matter what people think, DOS batch scripts are just as alive and needed as ever. And for all the tasks we create on Windows servers, we still commonly need to gather application output, rotate logs, etc.
So when running a script that exports results to a log/results file, I always prefer to date my file names for easy tracking and history. My preferred date arrangement for filenames is the date in reverse format: YYYYMMDD, or 20120809. And since the DOS
date command isn’t as friendly or flexible as the Linux/Unix
date command (with which you may easily format the output in myriad ways), it’s best to do the next-best thing: use the
Most folks don’t even know that your Windows system is keeping a real-time variable for the date, but it certainly makes sense that it would be necessary. Go ahead, pull up a command prompt and type:
…and on a Windows XP workstation, you’ll get a result like this:
So what we need to do now is to utilize string manipulation, grab the date elements we want, and flip the order around to get the arrangement we need:
The structure above is this: There are 3 sections, all of which use the date variable. The first section moves in 6 characters, and grabs 4 for the year. The second starts at 0 (zero, the beginning) characters and grabs 2 (for the month), and the third moves in 3 and grabs 2 (for the day). As a result, we have reverse-date!
Then we can set a variable to use the combined date variable in the filename like this:
…now just call the
%exportfile% in your batch file when you redirect your output, and viola!! Here’s what it looks like when you