windowsbatch-file

Windows Batch to select a COM port number


I have an old batch file that start an exe passing some hardcoded parameters, and I need to make it more flexible.

One of those parameters is the serial port number to use, and what I want now is to prompt the used to pick the right one.

I've found this great answer to find and show the ports descriptions. On my PC, it shows this list:

_COM1=Porta di comunicazione
_COM2=Porta di comunicazione
_COM5=USB Serial Port
_COMRealtek RealManage COM1=Realtek RealManage COM1
_COMRealtek RealManage COM2=Realtek RealManage COM2

What i would like is:

So, in my case, i would like to show to the user something like this:

Please select what COM port to use:
  1 - COM1=Porta di comunicazione
  2 - COM2=Porta di comunicazione
  5 - COM5=USB Serial Port
or press ESC to exit.

How could it be done?


Solution

  • This is the final code i've sort out.

    The idea is to check if the answer from the user is in the string with all the available COM ports. This 'cause choice won't allow double-digit port numbers (like "13" if there's a "COM13").

    The code isn't super-tested right now, but it seems to work.

    @echo off
    Setlocal EnableDelayedExpansion
    
    cls
    
    rem initialize variables
    set "Port_List=Q"
    set wmic_command=wmic path win32_pnpentity where "PNPClass Like 'Ports'" get caption /format:list
    
    rem execute wmic and get a list of all COM ports, real or virtual
    for /f "tokens=1* delims==" %%I in ('%wmic_command% ^| find "COM"') do (
        rem process each returned line to create the menu and get the port numbers
        call :setCOM "%%~J"
    )
    echo=
    
    rem No available ports, exit
    if "%Port_List%"=="" (
        echo No serial ports found.
        goto uscita
    )
    
    :input_loop
    set /p userInput=Please type the COM port number, or "Q" to quit:
    
    rem Check if the input is 'Q' (case-insensitive)
    if /i "%userInput%"=="Q" (
        echo End.
        goto uscita
    )
    rem "enclose" the answer, to catch 2-digits port numbers
    set "SELECTED_PORT=,%userInput%_"
    
    rem Check if the selected port (with comma) exists in the built Port_list string
    echo %Port_List% | findstr /c:"%SELECTED_PORT%" >nul
    if errorlevel 1 (
        echo Error: Port %userInput% does not exists. Retry.
        goto input_loop
    )
    
    echo You selected port %userInput%.
    goto uscita
    
    rem end main batch
    :uscita
    endlocal
    exit /b
    
    :setCOM <WMIC_output_line>
    set "str=%~1"
    set "num=%str:*(COM=%"
    set "num=%num:)=%"
    rem "enclose" the number, to catch 2-digits port numbers
    set "Port_List=%Port_List%,%num%_"
    set str=%num% - %str%
    echo   %str%
    goto :EOF