Tuesday, March 27, 2007

Fun with command line variables

Some time ago I needed to set up a log rotation, renaming an existing log file to the current time and date. The thing is dutch dates use a comma and you can't have that. I needed a way to cut the time and date variables in pieces and create my own time and date notation.

I could have used some tools but I like to use the standard Windows tools. I decided to use the set command which has some nice operators:

Set the variable hour to the first 2 characters of the time (offset 0):
set hour=%time:~0,2%

Set the variable minute to the 4th and 5th characters of the time (offset 3):
set minute=%time:~3,2%

Set the variable seconds to the 6th and 7th characters of the time (offset 6):
set second=%time:~6,2%

Then add everything together: copy logfile "C:\Logfiles\%hour%.%minute%.%second%.log"

I just realised that you don't even need to store the hours, minutes and seconds in termporary values. The command copy logfile "C:\Logfiles\%time:~0,2%.%time:~3,2%.%time:~6,2% works just as nice!

1 comment:

David Pierson said...

Excellent, just what I was looking for. I would consider myself an experienced programmer but had no idea of this percent-time feature. Thank you Rogier !