在Windows CLI上使用时间戳记Ping [英] Ping with timestamp on Windows CLI
问题描述
在Windows命令提示符 cmd
上,我使用 ping -t到10.21.11.81
On the Windows command prompt cmd
, I use ping -t to 10.21.11.81
Reply from 10.21.11.81: bytes=32 time=3889ms TTL=238
Reply from 10.21.11.81: bytes=32 time=3738ms TTL=238
Reply from 10.21.11.81: bytes=32 time=3379ms TTL=238
是否有可能获得这样的输出?
Are there any possibilities to get an output like this?
10:13:29.421875 Reply from 10.21.11.81: bytes=32 time=3889ms TTL=238
10:13:29.468750 Reply from 10.21.11.81: bytes=32 time=3738ms TTL=238
10:13:29.468751 Reply from 10.21.11.81: bytes=32 time=3379ms TTL=238
请注意,我只想使用CMD提供的命令来实现这一点
Please note that I wanna achieve this with only commands provided by CMD
推荐答案
@echo off
ping -t localhost|find /v ""|cmd /q /v:on /c "for /l %%a in (0) do (set "data="&set /p "data="&if defined data echo(!time! !data!)"
note :要在批处理文件中使用的代码.要从命令行使用,请用%a
note: code to be used inside a batch file. To use from command line replace %%a
with %a
启动ping命令,强制输入正确的行缓冲输出( find/v
),并启动启用延迟扩展的 cmd
进程,该进程将无限循环读取将以当前时间为前缀的管道数据将回显到控制台.
Start the ping, force a correct line buffered output (find /v
), and start a cmd
process with delayed expansion enabled that will do an infinite loop reading the piped data that will be echoed to console prefixed with the current time.
2015-01-08 已编辑:在较快/较新的机器/操作系统版本中,先前的代码中存在一个同步问题,使 set/p
读取一行,而 ping
命令仍在写入该行,并且结果是剪线.
2015-01-08 edited:
In faster/newer machines/os versions there is a synchronization problem in previous code, making the set /p
read a line while the ping
command is still writting it and the result are line cuts.
@echo off
ping -t localhost|cmd /q /v /c "(pause&pause)>nul & for /l %%a in () do (set /p "data=" && echo(!time! !data!)&ping -n 2 localhost>nul"
子shell的开头包含两个附加的 pause
命令(只能使用一个,但是由于 pause
使用了一个输入字符,因此CRLF对被打断并且读取带有LF的行)以等待输入数据,并包含一个 ping -n 2本地主机
以在内部循环中为每次读取等待一秒钟.结果是行为更加稳定,CPU使用率更低.
Two aditional pause
commands are included at the start of the subshell (only one can be used, but as pause
consumes a input character, a CRLF pair is broken and a line with a LF is readed) to wait for input data, and a ping -n 2 localhost
is included to wait a second for each read in the inner loop. The result is a more stable behaviour and less CPU usage.
注意:内部的 ping
可以替换为 pause
,但是随后,每个读取的行的第一个字符都会被 pause
占用.而不是通过 set/p
NOTE: The inner ping
can be replaced with a pause
, but then the first character of each readed line is consumed by the pause
and not retrieved by the set /p
这篇关于在Windows CLI上使用时间戳记Ping的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!