Multiline FOR and %TIME%

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?
 
F

foxidrive

(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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top