\[Editor's Note: Email your scripting solutions (400 words or less) to Reader to Reader at email@example.com. Please include your script and phone number. We edit submissions for style, grammar, and length. If we print your contribution, you receive $100.\]
Timestamping log files created by administrative shell scripts is useful. Although Windows 2000 has the %date% and %time% variables for easy timestamping, Windows NT 4.0 doesn't offer them.
In NT 4.0 systems, the most common timestamp methods are using the Microsoft Windows NT Server 4.0 Resource Kit utility called now.exe and logging the output of the Date /t and Time /t commands. However, using the Prompt command is a more elegant way to create a timestamp.
If you type
at the command line, an online Help display appears with a list of parameters that you can use with the Prompt command. The list includes the current date ($D) and current time ($T) parameters. You can use these two parameters to create a temporary prompt inside a new command shell with the code
Echo exit|cmd /q /k prompt $D $T
In this code, you use the Cmd /q /k command to start a new command shell. The Prompt $D $T command displays the date and time at which you started that shell. You send, or pipe, the Exit command's output to the command shell so that the shell ends immediately. The only output from the shell is the date and time.
To timestamp a log file, you redirect the output to that file. For example, to timestamp the file mylog.txt, you type
Echo exit|cmd /q /k prompt $D $T>>mylog.txt
You can use the Prompt command to add other information to files. For example, the code
Echo exit|cmd /q /k prompt running %~F0 from $P$_$D $T>>mylog.txt
adds two lines to mylog.txt. (Although this code appears on two lines here, when you type it at the command prompt, it needs to be all on one line.) One line in mylog.txt contains the filename and the current working directory. The other line in mylog.txt contains the timestamp.
You don't even need to know the date format (as set by the regional settings) to correctly extract the date for the timestamp. The code in Listing 1 breaks the date and time into components and returns those components in the variables
- dow (contains the day of the week, such as Sunday)
- dd (contains the day)
- mm (contains the month)
- yy (contains the year)
- hh (contains the hour)
- min (contains the minutes past the hour)
- ss (contains the seconds past the minute)
Thus, the code always returns the correct values for dd, mm, and yy, regardless of the format the date is in.