首先,我要说我是脚本新手...
我正在尝试创建一个可定期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
有什么方法可以使其在适当的时间更新吗?
附带说明一下,“ / l %% X in ...”无法弄清楚应实际代替%% X的内容。从谷歌搜索等等,我已经看到人们使用不同的浏览器,但是似乎无法弄清楚它指的是什么。如果有人也可以让我知道这一点,将不胜感激。
谢谢
在某一点上,实际上每个批处理脚本的人都会陷入延迟的扩展陷阱。
基本上,当第一次运行批处理脚本时,%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
完全可以),因为您没有直接使用它,而只是使用它运行了三次代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句