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 20120531. 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 Windows 7 and Server 2008 (for XP, please see this post), 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 10 characters, and grabs 4. The second moves in 4 characters and grabs 2, and the third moves in 7 and grabs 2. As a result, we have reverse-date!
Then set a variable to use the combined date variable in the filename.
…now just call the
%exportfile% in your batch file when you redirect your output, and viola!! Here’s what it looks like when you
(Updated 20120809 for OS version clarification)