Job for a boffin - DOS script reqd

Soldato
Joined
18 Oct 2002
Posts
8,448
Location
Scun'orp
I want to save to output of a dos command to a file. I know you can do this by using the redirect dos switch, i.e. dir >text.txt

However what I would like to do is make a script such that the name of the text file either takes the date/time or uses some other form of indexing such that it won't overwrite an existing text file, allowing me to schedule this command to be run and build up a set of output files, which I'm then going to analyse. I know you can use dir >>text.txt to simply append to an existing text file but I would rather have things separate. Any dos boffins about?
 
You can get the date by
Code:
@echo off
FOR /F "usebackq TOKENS=1 delims=/ " %%A IN (`DATE/T`) DO SET dd=%%A
FOR /F "usebackq TOKENS=2 delims=/ " %%B IN (`DATE/T`) DO SET mm=%%B
FOR /F "usebackq TOKENS=3 delims=/ " %%C IN (`DATE/T`) DO SET yyyy=%%C

SET filename=%dd%%mm%%yyyy%one.txt

dir > %filename%
 
Last edited:
Or, more efficiently,

Code:
@echo off
FOR /F "usebackq TOKENS=1-3 delims=/ " %%A IN (`DATE/T`) DO (
	SET dd=%%A
	SET mm=%%B
	SET yyyy=%%C
)

SET filename=%dd%%mm%%yyyy%one.txt

dir > %filename%

Beware though as the date command can return different results depending on system settings, if you are planning to run the script on multiple machines.

Also you might want the time, so full code would be
Code:
@echo off
FOR /F "usebackq TOKENS=1-3 delims=/ " %%A IN (`DATE/T`) DO (
	SET dd=%%A
	SET mm=%%B
	SET yyyy=%%C
)
FOR /F "usebackq TOKENS=1,2 delims=:" %%A IN (`TIME/T`) DO (
	SET H=%%A
	SET M=%%B
)

SET filename=%yyyy%%mm%%dd%%H%%M%.txt

Also, you should probably consider using the date format of YYYYMMDD as this has many benefits, not least of which sorting by date is a piece of cake.
 
Back
Top Bottom