Search code examples
batch-filetimeout

Batch: How to prompt for input and continue if timed out?


I know the timeout /t 60 way to get a delay with automatic continue and the set /p var="prompt" for getting user input but is there any change to do both; ask and have a timeout to continue if nothing is entered? I would use it for a sort of get set screen for my looping script to change script settings.


Solution

  • Take a look at choice /? to request a key and abort with a timeout.

    For example:

    CHOICE /T 10 /C YN /D Y
    

    will wait 10 seconds for Y (Yes) or N (No), otherwise the default (/D) will be taken, which is Y (Yes) in this example.

    To check the result (either keypressed or default value), you have to check %ERRORLEVEL%.

    @echo off
    cls
    CHOICE /T 5 /C YN /D Y
    set _e=%ERRORLEVEL%
    if %_e%==1 echo Y&goto :done
    if %_e%==2 echo N&goto :done
    
    echo Error
    echo %_e%
    
    :done