Search code examples
androidbatch-filewindows-10adb

Prompt user to select device (from line)


I'm trying to list the connected adb devices and prompt the user to select a line to deploy an APK to.

So far I've tried:

for %%i in (adb devices) do (
    ECHO %%i
)

But that won't work at all. Is there any way to capture the id of each adb device into variables? My goal if possible is to capture each id like:

%line1=f2ea3410

From adb listing adb devices:

f2ea3410        device
f2fa3410        device

So I can prompt the user the line (and not the id which is painful to type):

@ECHO OFF
set /p id="Enter Line:"

Solution

  • I tested this with the example you provided. Just modify :DoIt to do whatever it is you want to do with the available Id.

    @setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
    @rem @set prompt=$G
    
    @set _command=adb.cmd
    @set _count=0
    
    @for /f "tokens=1,*" %%G in ('%_command% devices') do @call :AddAndDisplayDevice %%G "%%H"
    @set /p _choice=Enter number from above menu:
    @if not defined _%_choice% @goto :BadSelection "%_choice%"
    @call :DoIt %_choice%
    @exit /b 0
    
    :AddAndDisplayDevice
    @set /a _count+=1
    @echo %_count%. %*
    @call :SetVar %_count% %1
    @call :SetVar %_count%_description %2
    @exit /b 0
    
    :BadSelection
    @rem Up to you whether to loop back and try again.
    @echo Bad choice: %_choice%
    @exit /b -1
    
    :DoIt
    @set _Id=!_%1!
    @rem set _
    @echo User selected %1, device Id %_Id%.
    @exit /b 0
    
    :SetVar
    @set _%1=%2
    @exit /b 0
    

    Adb.cmd, for testing:

    @echo f2ea3410        device
    @echo f2fa3410        device