Batch ERRORLEVEL ping response

前端 未结 13 1501
走了就别回头了
走了就别回头了 2020-12-14 23:05

I\'m trying to use a batch file to confirm a network connection using ping. I want to do batch run and then print if the ping was successful or not. The problem is that it a

相关标签:
13条回答
  • If you were to

    echo "Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),"
    

    you would see the % is stripped. You need to escape it as % has a special meaning within a batch file:

    "Packets: Sent = 4, Received = 4, Lost = 0 (0%% loss),"
    

    However its simpler to use TTL as the indication of success;

    .. | find "TTL"
    
    0 讨论(0)
  • 2020-12-14 23:45

    The most simple solution to this I can think of:

    set error=failure
    ping racer -n 1 -w 100>nul 2>&1 && set error=success
    

    Of course, -w needs to be adjusted if on a slow link (100ms might be too short over Dialup ;-))

    regards

    0 讨论(0)
  • 2020-12-14 23:45

    Yes ping fails to return the correct errorlevel. To check the network connection and the computer I used "net view computername" then checked %errorlevel% - simple and easy

    0 讨论(0)
  • 2020-12-14 23:48

    Another variation without using any variable

    ping racer -n 1 -w 100>nul || goto :pingerror
    ...
    
    :pingerror
    echo Host down
    goto eof
    
    :eof
    exit /b
    
    0 讨论(0)
  • 2020-12-14 23:49

    Based on Alex K's note, this works for me on Windows 7:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    
    for /f %%i in (PCS.TXT) do (
       SET bHOSTUP=0
       ping -n 2 %%i |find "TTL=" > NUL && SET bHOSTUP=1
       IF !bHOSTUP! equ 1 (
          CALL :HOSTUP %%i
       ) else (
          CALL :HOSTDOWN %%i 
       )
    )
    GOTO EOF
    
    :HOSTUP
    echo Host UP %1
    GOTO EOF
    
    :HOSTDOWN
    echo Host DOWN %1
    GOTO EOF
    
    :EOF
    exit /B
    
    0 讨论(0)
  • 2020-12-14 23:52

    I 'm not exactly sure what the interaction between FIND and setting the error level is, but you can do this quite easily:

    @echo off
    for /f %%i in ('ping racer ^| find /c "(0%% loss)"') do SET MATCHES=%%i
    echo %MATCHES%
    

    This prints 0 if the ping failed, 1 if it succeeded. I made it look for just "0% loss" (not specifically 4 pings) so that the number of pings can be customized.

    The percent sign has been doubled so that it's not mistaken for a variable that should be substituted.

    The FOR trick serves simply to set the output of a command as the value of an environment variable.

    0 讨论(0)
提交回复
热议问题