Multiline FOR and %TIME%

  • Thread starter Thread starter rpresser
  • Start date Start date
R

rpresser

(It is very difficult to search Google on this topic, because it
ignores the % punctuation in my search. Very provoking.)

As is well known, the %TIME% variable expands to the current time:

C:\>echo %TIME%
10:36:30.71

If I use it several times in a batch file that takes a nontrivial
amount of time, the later times are indeed later:

C:\>type test1.cmd
echo %TIME%
ping google.com >nul
echo %TIME%

C:\>test1

C:\>echo 10:37:19.86
10:37:19.86

C:\>ping google.com 1>nul

C:\>echo 10:37:23.55
10:37:23.55

But in a loop, apparently %TIME% is only expanded once and then
substituted the same on each loop pass:

C:\>type test2.cmd
for %%i in (1 2 3) do echo %%i 10:38:28.91 & ping -n 2 google.com >nul

C:\>test2

C:\>for %i in (1 2 3) do echo %i 10:38:28.91 & ping -n 2 google.com
1>nul

C:\>echo 1 10:38:28.91 & ping -n 2 google.com 1>nul
1 10:38:28.91

C:\>echo 2 10:38:28.91 & ping -n 2 google.com 1>nul
2 10:38:28.91

C:\>echo 3 10:38:28.91 & ping -n 2 google.com 1>nul
3 10:38:28.91

The other traditional way to get the time, using for with delims and
TIME /T, doesn't get me the seconds, which I need. Any other way to
get the current time while in a loop?
 
(It is very difficult to search Google on this topic, because it
ignores the % punctuation in my search. Very provoking.)

As is well known, the %TIME% variable expands to the current time:

C:\>echo %TIME%
10:36:30.71

If I use it several times in a batch file that takes a nontrivial
amount of time, the later times are indeed later:


But in a loop, apparently %TIME% is only expanded once and then
substituted the same on each loop pass:


The other traditional way to get the time, using for with delims and
TIME /T, doesn't get me the seconds, which I need. Any other way to
get the current time while in a loop?

@echo off
setlocal EnableDelayedExpansion
for %%i in (1 2 3) do echo %%i !time! & ping -n 2 google.com >nul
 
Back
Top