Search code examples
batch-filebatch-choice

batch file choice command when more than 10 number


I just want to list all my Interface Network and choose one. BUT, I have more than 10 Interface (12 actually) and then got an error. Cannot make then a choice How can I use ABCDEFGHIJKLMNOPQ... in place of 12345678... Here is my code :

'''

@echo off
cls
setLocal enableDelayedExpansion
set c=0
set "choices="

echo Your Interfaces -

for /f "skip=2 tokens=3*" %%A in ('netsh interface show interface') do (

    set /a c+=1
    set int!c!=%%B
    set choices=!choices!!c!
    echo [!c!] %%B
)

choice /c !choices! /m "Select The Number of Your Interface Please: " /n

set interface=!int%errorlevel%!
set Connex="%interface%"

'''


Solution

  • By adding a function that converts the given index to a character out of a given list keys, you can add more options. As errorlevel starts with 1, the 0 index can never be used, so that is just populated by a useless _. You can add any character (that is valid inside the choice command) to keys list. If you want to starts with numbers and then letters you can for example do this set keys=_123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ

    @echo off
    cls
    setLocal enableDelayedExpansion
    set c=0
    set "choices="
    echo Your Interfaces -
    
    for /f "skip=2 tokens=3*" %%A in ('netsh interface show interface') do (
        
        set /a c+=1
        
        call :ResolveChar !c!
        
        set int!retval!=%%B
        set choices=!choices!!retval!
        echo [!retval!] %%B
    )
    
    choice /c !choices! /m "Select The Number of Your Interface Please: " /n
    
    call :ResolveChar %errorlevel%
    set interface=!int%retval%!
    set Connex="%interface%"
    echo %Connex%
    
    goto :eof
    
    :ResolveChar
    SETLOCAL
      set keys=_ABCDEFGHIJKLMNOPQRSTUVWXYZ
      set _startchar=%1
      CALL SET char=%%keys:~%_startchar%,1%%
    ENDLOCAL & SET retval=%char%
    
    goto :eof