【问题标题】:Batch File Filter loop output批处理文件过滤器循环输出
【发布时间】:2022-01-22 05:45:34
【问题描述】:

代码运行一个非常简单的过程,无休止地 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

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

【问题讨论】:

    标签: batch-file filter nested-for-loop


    【解决方案1】:
    :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
    

    (我对使用关键字/可执行名称作为标签过敏)

    只需将标志值pung 设置为nothing,以便在pings 启动时它是未定义的。在报告第一行时,将pung 设置为非空,因此它是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,如果是,只写报告。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 2019-11-13
      • 1970-01-01
      • 2023-03-23
      • 2023-04-08
      • 2015-09-17
      • 1970-01-01
      相关资源
      最近更新 更多