Batch File: Getting user input during execution of other commands, then checking it later

僤鯓⒐⒋嵵緔 提交于 2019-12-13 19:57:20

问题


What I want is a command (or series of commands) that works with Windows 7, 8.1, and 10. It needs to collect user input at any time during the execution of the batch file it's in, only to checked and interpreted later. I do not mind using an input text file.

I've already searched for an answer, but the closest I've come to it is <nul set /p "input=", but it requires the user to press a key and hit enter at the exact moment the command is run. Any help would be greatly appreciated.


回答1:


This method utilizes GOTO to create a loop which checks the first line of input.txt every 6 seconds or so. You could replace the content of :DOSTUFF with anything you want. Let me know if you have questions.

@echo off
GOTO DOSTUFF

:CHECKINPUT
    for /f %%a in (input.txt) do (
        if %%a NEQ "" (
            set "input=%%a"
            GOTO GOTINPUT
            )
        exit /b
    )
    GOTO DOSTUFF

:GOTINPUT
    echo Thanks for the input!
    echo Here is what you entered:
    echo %input%
    GOTO ENDER
:DOSTUFF
    echo I could be doing other things here, but instead I'm just waiting for input...
    PING 127.0.0.1 -n 6 >nul
    GOTO CHECKINPUT
:ENDER
    pause

While this was running in one window, I just ran echo test>input.txt in another command prompt.

To make this more robust you might want to overwrite the file after you check it. This can easily be done with echo.>input.txt



来源:https://stackoverflow.com/questions/36775423/batch-file-getting-user-input-during-execution-of-other-commands-then-checking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!