Windows 批处理错误级别 ping 在循环中不起作用

问题描述 投票:0回答:1

有人可以帮忙找出以下批处理代码中的问题是什么吗? 我想检查 ip 192.168.0.1 的设备是否已准备好连接。 我关闭设备电源并在执行批处理后打开它。 如果第一次检查不为 0,则 %errorlevel% 似乎不起作用

@echo off

set "host=192.168.0.1"

for /l %%i in (1,1,255) do (
    ping -n 1 "%host%" | findstr /r /c:"[0-9] *ms"
    if %errorlevel% == 0 (
        echo ping %host% ok.
        goto :endLoop
    ) else (
        echo ping %host% fail count %%i
        REM "ping -n 6 -w 1000 " sleep 5 seconds
        ping 127.0.0.1 -n 6 -w 1000 > nul
    )
)

:endLoop
echo Done

我得到以下日志,当 ping 响应成功时它无法停止。

D:\document\code\windows\bat>check_ip.bat
ping 192.168.0.1 fail count 1
ping 192.168.0.1 fail count 2
ping 192.168.0.1 fail count 3
...
ping 192.168.0.1 fail count 21
ping 192.168.0.1 fail count 22
ping 192.168.0.1 fail count 23
Reply from 192.168.0.1: bytes=32 time=1ms TTL=64
    Minimum = 1ms, Maximum = 1ms, Average = 1ms
ping 192.168.0.1 fail count 24
Reply from 192.168.0.1: bytes=32 time=2ms TTL=64
    Minimum = 2ms, Maximum = 2ms, Average = 2ms
ping 192.168.0.1 fail count 25
Reply from 192.168.0.1: bytes=32 time=1ms TTL=64
    Minimum = 1ms, Maximum = 1ms, Average = 1ms
ping 192.168.0.1 fail count 26
Reply from 192.168.0.1: bytes=32 time=1ms TTL=64
    Minimum = 1ms, Maximum = 1ms, Average = 1ms
ping 192.168.0.1 fail count 27
^CTerminate batch job (Y/N)? Y

我在 Windows 10 机器上尝试了批处理。 我希望代码可以在 ping 响应成功后停止。

for-loop batch-file ping errorlevel
1个回答
0
投票
@echo off
setlocal enabledelayedexpansion

REM Define the IP address or hostname to ping
set "host=192.168.0.1"

REM Loop 100 times
for /L %%i in (1,1,255) do (
    echo Pinging attempt %%i
    ping -n 1 !host! >nul
    if !errorlevel! == 0 (
        echo ping %host% ok on attempt %%i
        goto :endLoop
    )
    REM Optional: Add a delay between pings
    timeout /t 1 >nul
)

:endLoop
echo Script finished

删除

| findstr /r /c:"[0-9] *ms"

如果没有,您将始终得到 findstr 错误级别,而不是 ping 错误级别。

© www.soinside.com 2019 - 2024. All rights reserved.