批处理脚本循环变量

时间:2012-11-22 17:36:07

标签: windows variables batch-file

这很简单,我不知道我敢打赌,我感觉它因为嵌套循环而无法按照我需要的方式工作。这是一个简单的脚本,我已经在某个地方取消并修改了一些以允许更多测试。从本质上讲,它只会一直延迟主机延迟,直到你关闭它,但记录失败的响应。一切正常,但对于我的生活,我无法弄清楚如何让它更新for循环中使用的名称。

@echo off
setlocal enabledelayedexpansion

:: ** Enter name to identify host in log **
set name1=Test 1
set name2=Test 2
set name3=Test 3

:: ** Enter IP or HOSTNAME to test against **
set hostIP1=1.1.1.1
set hostIP2=2.2.2.2
set hostIP3=3.3.3.3

:: ** Enter Delay in milliseconds between each test **
set delayMS=2000


title -DO NOT CLOSE- Ping Test
echo DO NOT CLOSE
echo Ping Test


:loop
set namecount=1
for %%x in (%hostIP1% %hostIP2% %hostIP3%) do (
set pingline=1
set pingname=name!namecount!
for /f "delims=" %%A in ('ping -n 1 -w 2000 -l 255 %%x') do (
    if !pingline! equ 2 (
        set logline=!date! !time! "%%A" - %%x !%pingname%!
        echo !logline! | find "TTL=">nul || echo !logline! >> pinglog.txt
        )
    set /a pingline+=1
    )
set /a namecount+=1
)
sleep -m %delayMS%
goto loop

通常我会使用另一种语言,但我需要适用于各种Windows服务器的东西。这似乎是最可靠的方法。感谢

1 个答案:

答案 0 :(得分:0)

这是不正确的:

!%pingname%!

试试这个:

!Pingname!

我无法尝试您的代码,但我做了其他一些小修改:

(修订版)

 @echo off
setlocal enabledelayedexpansion

:: ** Enter name to identify host in log **
set "name1=Test 1"
set "name2=Test 2"
set "name3=Test 3"

:: ** Enter IP or HOSTNAME to test against **
set "hostIP1=1.1.1.1"
set "hostIP2=2.2.2.2"
set "hostIP3=3.3.3.3"

:: ** Enter Delay in milliseconds between each test **
set /A "delayMS=2000"


title -DO NOT CLOSE- Ping Test
Echo DO NOT CLOSE
Echo Ping Test

:loop
set /A "namecount=1"
for %%x in (%hostIP1% %hostIP2% %hostIP3%) do (
    set /A "pingline=1"
    call set "pingname=%%name!namecount!%%"
    for /f "delims=" %%A in ('ping -n 1 -w 2000 -l 255 %%x') do (
        if !pingline! equ 2 (
            set "logline=%date% !time! %%A - %%x !pingname!"
            (echo !logline! | find "TTL=">nul) || (echo !logline! >> "pinglog.txt")
        )
        set /a "pingline+=1"
    )
    set /a "namecount+=1"
)
sleep -m %delayMS%
goto :loop