windowsbatch-filemenuselection

Selection menu in batch?


is it possible to have a batch script to ask the user (within CMD) to select if the current PC is a host or client? The user uses the up or down keyboard arrows to select an option and hits enter to confirm it.

Ive Done a little googling but I can only find code for entering a selection number.


Solution

  • There is no way that a Batch file can read a cursor control key without the aid of a third party program. However, you may use an interesting trick based on DOSKEY command via this procedure:

    1. Clear previous DOSKEY history.
    2. Execute several SET /P commands that read the menu options, so the DOSKEY history is filled with them.
    3. Send a F7 key to the keyboard.
    4. Execute a SET /P "OPTION=Prompt: "; the input to this command will be completed via the selection menu of DOSKEY.

    Although this method requires the aid of JScript programming language, it is included with all Windows versions from XP on. Copy and paste the code below as a Batch .BAT file:

    @if (@CodeSection == @Batch) @then
    
    
    @echo off
    setlocal EnableDelayedExpansion
    
    rem Multi-line menu with options selection via DOSKEY
    rem Antonio Perez Ayala
    
    rem Define the options
    set numOpts=0
    for %%a in (First Second Third Fourth Fifth) do (
       set /A numOpts+=1
       set "option[!numOpts!]=%%a Option"
    )
    set /A numOpts+=1
    set "option[!numOpts!]=exit"
    
    rem Clear previous doskey history
    doskey /REINSTALL
    rem Fill doskey history with menu options
    cscript //nologo /E:JScript "%~F0" EnterOpts
    for /L %%i in (1,1,%numOpts%) do set /P "var="
    
    :nextOpt
    cls
    echo MULTI-LINE MENU WITH OPTIONS SELECTION
    echo/
    rem Send a F7 key to open the selection menu
    cscript //nologo /E:JScript "%~F0"
    set /P "var=Select the desired option: "
    echo/
    if "%var%" equ "exit" goto :EOF
    echo Option selected: "%var%"
    pause
    goto nextOpt
    
    
    @end
    
    var wshShell = WScript.CreateObject("WScript.Shell"),
        envVar = wshShell.Environment("Process"),
        numOpts = parseInt(envVar("numOpts"));
    
    if ( WScript.Arguments.Length ) {
       // Enter menu options
       for ( var i=1; i <= numOpts; i++ ) {
          wshShell.SendKeys(envVar("option["+i+"]")+"{ENTER}");
       }
    } else {
       // Enter a F7 to open the menu
       wshShell.SendKeys("{F7}{HOME}");
    }
    

    Output example of previous program:

    Output example of previous program

    Further details at this post.