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

但是,时间戳始终保持不变。它应该将时间显示为大约 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/

相关文章:

shopify - Liquid 中的逗号分隔列表

git - 在 git 中恢复大多数前 n 个提交

python - Django 休息框架 : How serialize list of list?

c# - 使用 UpdateAsync 方法 ASP.NET Entity Framework

selenium - 如何 'click' 单选按钮 -> 需要 xPath

docker - 学习 docker 的先决条件

c# - 使用 Prism 库将 View 注入(inject) TabControl

c# - 将浮点指针作为 IntPtr 传递(pinvoke)

r - 如何在 R 中以固定网格模式绘制 "matrix"

r - 在 R 中将字符串拆分为固定长度元素的最快方法