首先我会说我是脚本编写的新手...
我正在尝试创建一个批处理文件来定期对主机执行 ping 操作。目前,我只是在本地 PC 上对其进行测试。到目前为止,这是我得到的:
@echo off
set SERVERNAME=127.0.0.1
set limit=3
ECHO %date%, %time% Starting ping test to localhost>>c:\users\%username%\desktop\Pingtest.txt
for /l %%X in (1,1,%limit%) do (
ping %servername% -n 3 | FIND "Reply" >>c:\users\%username%\desktop\Pingtest.txt
echo %time% >>c:\users\%username%\desktop\Pingtest.txt
Timeout /t 5
)
Exit
但是,时间戳始终保持不变。它应该将时间显示为大约 5 秒后(或超时值设置的时间),但与第一个时间戳保持相同。这是输出示例:
25/08/2015, 2:09:18.34 Starting ping test to localhost
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
2:09:18.34
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
2:09:18.34
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
2:09:18.34
有什么办法让它在适当的时间更新吗?
作为旁注,“for/l %%X in...”我想不出应该用什么来代替 %%X。从谷歌搜索等,我看到人们使用不同的,但似乎无法弄清楚它指的是什么。如果有人也能让我知道这一点,将不胜感激。
谢谢
最佳答案
在某一时刻,几乎每个批量编写脚本的人都会落入 delayed expansion 中。陷阱。
基本上,当批处理脚本首次运行时,%variable%
格式的变量会被替换为它们的实际值。当代码块内有代码时(即在 (
和 )
之间),变量可能需要更新,但不能更新,因为变量的存在已经被它的值所取代。要解决这个问题,您可以将 setlocal enabledelayedexpansion
放在脚本的顶部,然后使用 !variable!
格式 - 这告诉脚本这些需要保持可变。
@echo off
setlocal enabledelayedexpansion
set SERVERNAME=127.0.0.1
set limit=3
for /l %%X in (1,1,%limit%) do (
ping %servername% -n 3 | FIND "Reply" >>c:\users\%username%\desktop\Pingtest.txt
echo !time! >>c:\users\%username%\desktop\Pingtest.txt
Timeout /t 5
)
对于您的旁注,%%X
只是选择在 for 循环中使用的变量。它只能是一个字母长,这基本上是批处理变量区分大小写的唯一时间。在您的情况下,它可以是任何东西(%%X
完全可以),因为您没有直接使用它,而只是使用它来运行代码三次。
https://stackoverflow.com/questions/32194107/