批处理文件过滤器循环输出

Batch File Filter loop output

代码运行一个非常简单的过程,不断地 ping 多个地址并将结果输出到日志文件,直到手动停止。

@echo off
title ping_logger
set d1=%date:~4%
set d2=%d1:/=-%
set t1=%time::=.%
set t2=%t1: =%
set host=X.X.X.1;X.X.X.162
set hostname=%host:;=+%
set pinghostname=%host:;= and %
set logfile=Log_%hostname%_%ComputerName%_%d2%_%t2%.csv
setlocal enableextensions ENABLEDELAYEDEXPANSION
set counter=0
for %%A IN (%host%) DO (
    set /a counter+=1
)
endlocal && set counter=%counter%
echo Target Host(s) = %host%>%logfile%
echo Pinging %pinghostname% with 32 bytes of data: >>%logfile%
timeout %counter% >NUL
:Ping
FOR %%A IN (%host%) DO (
    for /F "tokens=* skip=2" %%A in ('ping %%A -n 1 ') do (
        echo %date:~4%, %time:~0,2%:%time:~3,2%:%time:~6,2%, %%A>>%logfile%
        echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2%, %%A
    )
)
IF (%counter% LSS 2)  timeout 1 >NUL
GOTO Ping

输出在日志文件中捕获了太多内容。我希望只从每个响应中获取第一行,例如突出显示的行

:DoPing
FOR %%A IN (%host%) DO (
    set "pung="
    for /F "tokens=* skip=2" %%A in ('ping %%A -n 1 ') do  if not defined pung (
        echo %date:~4%, %time:~0,2%:%time:~3,2%:%time:~6,2%, %%A>>%logfile%
        echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2%, %%A
        set "pung=Y"
    )
)
IF (%counter% LSS 2)  timeout 1 >NUL
GOTO DoPing

(我对使用 keywords/executable 名称作为标签过敏)

只需将标志值 pung 设置为 nothing 以便在 ping 开始时未定义。上报第一行,设置pung为non-empty,则为defined,重挖报告行被抑制

%%A 的下一个循环在为下一个主机发出 ping 之前清除 pung...


另一种方式:

:DoPing
FOR %%A IN (%host%) DO (
    for /F "tokens=1* skip=2" %%A in ('ping %%A -n 1 ') do if "%%A" == "Reply" (
        echo %date:~4%, %time:~0,2%:%time:~3,2%:%time:~6,2%, %%A %%B>>%logfile%
        echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2%, %%A %%B
    )
)
IF (%counter% LSS 2)  timeout 1 >NUL
GOTO DoPing

这次,看第一个token是不是字符串Reply,只有是才写报告。