echo %time% 重复输出

echo %time% 重复输出

我有一个命令,在开始和结束时添加时间戳(echo %time% & #other command# & echo %time%)。但是,%time%无论命令执行多长时间, 都将相同。

示例输出:

Time start: 19:48:31.75

Pinging google.com [2a00:1450:400e:80c::200e] with 32 bytes of data:
Reply from 2a00:1450:400e:80c::200e: time=13ms
Reply from 2a00:1450:400e:80c::200e: time=13ms
Reply from 2a00:1450:400e:80c::200e: time=9ms
Reply from 2a00:1450:400e:80c::200e: time=10ms

Ping statistics for 2a00:1450:400e:80c::200e:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 9ms, Maximum = 13ms, Average = 11ms

Time end: 19:48:31.76

有没有办法完成这个工作,并且仍然在一行之内?

谢谢

答案1

CMD 会扩展变量,然后执行每一行。这意味着

echo %time% & ping 127.0.0.1 & echo %time%

首先被展开,然后被执行

还有“延迟扩张” 以下是一些示例用法甚至更详细 但是这只在 cmd 文件中有效,而在命令行中无效。

setlocal ENABLEDELAYEDEXPANSION
echo !time! & ping 127.0.0.1 & echo !time!

继续搜索也许是 cmd /V可用于:

cmd /V /C "echo %time% & ping 127.0.0.1 & echo !time!"

它给了我预期的结果,但可能会存在阻碍某些用例的陷阱。

相关内容