This shows the ability of DOS to parse strings, and the use of system variables, namely the %date% var. It uses the optional parsing parameters, :~#,# where the first number is where to start (the first character is 0) and the second number is how many characters to take. It took me a couple hours to figure all this out the other day, I hope I can save you the pain I suffered.
@echo off cls echo This will create a subdirectory with today's date as the name. echo The date looks like this: %date% echo We'll use %%date%% echo and take the last 4 characters (the year) using :~-4,4 echo The -4 is "4 in from the right" and 4 is the number of characters to take. echo --- echo The command looks like this in the batch file: echo md %%date:~-4,4%%\%%date:~-10,2%%\%%date:~-7,2%% echo --- echo but to DOS it looks like this: echo md %date:~-4,4%\%date:~-10,2%\%date:~-7,2% echo --- pause @echo on md %date:~-4,4%\%date:~-10,2%\%date:~-7,2%
Updated 7/18/2007:
Here is how to do an action and log the output to a daily log file. I find this useful for my batch file that erases blacklisted emails from my Exchnage server. For this example, I'll just show you using the DIR command. Any dos program or batch file that outputs text to the console can be redirected to a file.
dir >log_%date:~-4,4%.%date:~-10,2%.%date:~-7,2%.txtThis is easy... the DIR command outputs the contents of the directory as a list in plain text. We are redirecting the output of this operation to a file. The filename will start with the word log_ and look like this: log_2007.07.18.txt.
But what if you want the process to run every 30 minutes, and add lines to the log file all day, rather than replace it? just double up the > like this:
dir >>log_%date:~-4,4%.%date:~-10,2%.%date:~-7,2%.txtNow the dir command will add lines to the same file rather than overwriting the previous run.
other possibilities:
pkzip *.jpg images_%date:~-4,4%.%date:~-10,2%.%date:~-7,2%.zip -m del *.tmp >deleted_%date:~-4,4%.%date:~-10,2%.%date:~-7,2%.log md archive_%date:~-4,4%\%date:~-10,2%\%date:~-7,2%I hope this helps!
56 comments: