batch-fileping

How to ping a server only once from within a batch file?


I want to learn how to write batch scripts and tried to create a script which automatically runs this command in the command line once:

ping www.google.de -t

and displays the ping, so it would look like this:

Reply from XXX.XXX.X.XX: time=30ms
Reply from XXX.XXX.X.XX: time=31ms
Reply from XXX.XXX.X.XX: time=29ms

My problem is, that this will result in this when I execute this command as script:

Screenshot showing output on running the batch file.

My problem is that it will not execute the ping command at all, but just insert the command unlimited times in the console window as its shown in the screenshot.

I just created a new file, wrote ping www.google.de -t in it, saved it as ping.bat file and executed it with double clicking on it.

So how to write the batch file to start this command only once and display the ping result?


Solution

  • Enter in a command prompt window ping /? and read the short help output after pressing RETURN. Or take a look on:

    Explanation for option -t given by Microsoft:

    Specifies ping continue sending echo Request messages to the destination until interrupted. To interrupt and display statistics, press CTRL+ENTER. To interrupt and quit this command, press CTRL+C.

    You may want to use:

    @%SystemRoot%\System32\ping.exe -n 1 www.google.de
    

    Or to check first if a server is available:

    @echo off
    set MyServer=Server.MyDomain.de
    %SystemRoot%\System32\ping.exe -n 1 %MyServer% >nul
    if errorlevel 1 goto NoServer
    
    echo %MyServer% is available.
    rem Insert commands here, for example one or more net use to connect network drives.
    exit /B
    
    :NoServer
    echo %MyServer% is not available yet.
    pause
    exit /B
    

    The exit code of PING is unfortunately also 0 if the destination host is unreachable. A better solution is therefore checking if the output of PING contains TTL= as in this case the destination host definitely responded on the ICMP ECHO request.

    @echo off
    set MyServer=Server.MyDomain.de
    %SystemRoot%\System32\ping.exe -n 1 %MyServer% | %SystemRoot%\System32\find.exe "TTL=" >nul || goto NoServer
    
    echo %MyServer% is available.
    rem Insert commands here, for example one or more net use to connect network drives.
    exit /B
    
    :NoServer
    echo %MyServer% is not available yet.
    pause
    exit /B
    

    The conditional command operator || with goto NoServer is like using one more command line after the PING command line with the FIND command with if errorlevel 1 goto NoServer. See single line with multiple commands using Windows batch file for a detailed description of the conditional command operators || and &&.

    The destination host availability check on destination host being in local area network can be speed up by inserting after -n 1 additionally the PING option -w 500 to wait only up to 500 ms for the ICMP ECHO respond.