批处理文件中的时间戳未正确更新

jak*_*obo 2 batch-file

我首先要说我对脚本很陌生...

我正在尝试创建一个定期 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
Run Code Online (Sandbox Code Playgroud)

但是,时间戳始终保持不变。它应该将时间显示为大约 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 
Run Code Online (Sandbox Code Playgroud)

有没有办法让它在适当的时间更新?

作为旁注,“for /l %%X in...”我不知道我应该用什么来代替 %%X。从谷歌搜索等,我看到人们使用不同的,但似乎无法弄清楚它指的是什么。如果有人也能让我知道这一点,我将不胜感激。

谢谢

Som*_*ark 6

在某一时刻,几乎每个批量编写脚本的人都会陷入延迟扩展陷阱。

基本上,当第一次运行批处理脚本时,%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
)
Run Code Online (Sandbox Code Playgroud)

对于您的旁注,%%X只是选择在 for 循环中使用的变量。它只能是一个字母长,并且基本上是批处理变量区分大小写的唯一一次。在您的情况下,它可以是任何东西(%%X非常好),因为您没有直接使用它,而只是使用它来运行代码三次。