See the comments at the end for corrected versions of the code.
I recently bought a new 250GB external hard disk (a Buffalo HD-HB250U2-1 USB 2.0 Drivestation 250GB External Hard Drive ) – it seems very quiet and fast. I decided to create a DOS batch file to do backups (I’ve never found a graphical backup program that I like and trust).
The copying itself is pretty straightforward – just use xcopy, supplying it with flags to copy file attributes and only to back up files that are newer than the existing backed-up versions.
The tricky bit was that I wanted to display the elapsed time. For example, if I choose to run the script automatically in the middle of the night, I’d like to know how long it took. Printing the current time at any point (e.g. at the start) is straightforward: ECHO %TIME% would do. However, I’m too lazy to work out the difference between two times by hand, and figured that it must be easy to get the batch file to do this automatically. Well, it wasn’t as easy as I thought, but after much faffing around with poorly documented DOS commands that don’t work the way I expected, I present the following method for displaying the elapsed time (note that I’ve used underscores at the end of lines where they are too wide to fit here). Enjoy.
:: Set START_TIMESTAMP as the number of :: minutes so far today FOR /F "tokens=1,2 delims=:" %%t in ('time/t') do SET /a _ START_TIMESTAMP=%%t * 60 + %%u :: ........................................ :: ... do time-consuming processes here ... :: ........................................ :: Work out the elapsed time expressed in minutes FOR /F "tokens=1,2 delims=:" %%t in ('time/t') do SET /a _ END_TIMESTAMP=%%t * 60 + %%u :: Do the correct calculation to account for roll-over :: (assumes the whole elapsed time is always less than :: 24 hours) IF %END_TIMESTAMP% GEQ %START_TIMESTAMP% ( SET /a ELAPSED_TIME=%END_TIMESTAMP% - %START_TIMESTAMP% ) :: ELSE IF %END_TIMESTAMP% LSS %START_TIMESTAMP% ( SET /a ELAPSED_TIME=%END_TIMESTAMP% + 1440 - _ %START_TIMESTAMP% ) :: Split elapsed time into hours and minutes SET /a ELAPSED_HOURS=%ELAPSED_TIME% / 60 SET /a ELAPSED_MINUTES=%ELAPSED_TIME% - _ (%ELAPSED_HOURS% * 60) :: The following could be piped to a log file, if required ECHO Backup took %ELAPSED_HOURS% hours and _ %ELAPSED_MINUTES% minutes. :: Tidy up SET START_TIMESTAMP= SET END_TIMESTAMP= SET ELASPED_TIME= SET ELASPED_HOURS= SET ELASPED_MINUTES=
The original version of this article on Blogger attracted a number of useful comments, so I’ve brought these across too.