loopsbatch-filecmdbreak

How can I interrupt a loop in CMD batch file using a specific key input?


here is the whole idea: I have a menu to test ping different DNS Servers in a batch file just like below:

:MainMenu
ECHO 1. DNS Server 1
ECHO 2. DNS Server 2

Now when the user chooses one of the options above, the process starts to ping the selected server in this case I use google DNS 8.8.8.8 :

:loopStarter
ECHO ***AUTO PING MODE IS ENABLED***
ECHO Pinging...
ping 8.8.8.8

CLS

GOTO loopStarter

As you can see this bunch of code creates a loop and pings the server and never stops,

HOWEVER

I want to stop the loop by entering a key (any key) to take me back to the :MainMenu

===========

I have seen and tested many answers like Here but unfortunately either I don't understand the code or it is not related to my problem.

I would appreciate it if anyone could guide me through.


Solution

  • Based on this method found here to create a dynamic menu, you can create something like that :


    @echo off
    :menuLOOP
    Title Pinging some DNS
    Color 9E & Mode 80,15
    ::===========================================================================
    echo(
    echo(
    echo(       ***************************** Menu ******************************
    echo(
    @for /f "tokens=2* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do (
    echo            %%A  %%B)
    echo(
    echo(       *****************************************************************
    echo( Make A Selection And Hit ENTER to Ping or simply hit ENTER to quit:
    Set /p Selection= || GOTO :EOF
    echo( & call :menu_[%Selection%]
    GOTO:menuLOOP
    ::===========================================================================
    :menu_[1] Ping DNS Server 1
    Cls
    ECHO( Pinging...
    ping 8.8.8.8
    echo( & echo( Type any key to return to the Main Menu
    pause>nul
    Goto:menuLoop
    ::---------------------------------------------------------------------------
    :menu_[2] Ping DNS Server 2
    Cls
    ECHO( Pinging...
    ping 8.8.4.4
    echo( & echo( Type any key to return to the Main Menu
    pause>nul
    Goto:menuLoop
    ::---------------------------------------------------------------------------