How can I exit a SET /p command after a certain time? For instance, if a user takes too long to input something, I want to exit the SET /p.
问题:
回答1:
This is a pure Batch solution that avoid the problems that the Batch-JScript hybrid script have when Sendkeys is used and the original window is not in focus.
@echo off
setlocal EnableDelayedExpansion
rem Execute a SET /P command with time out
rem Antonio Perez Ayala
rem If this file is re-executed as pipe's right side, go to it
if "%~1" equ "TimeoutMonitor" goto %1
del InputLine.txt 2> NUL
(
set /P "line=You have 10 seconds to complete this input: " > CON
> InputLine.txt call set /P "=%%line%%" < NUL
) 2> NUL | "%~F0" TimeoutMonitor 10
set /P "line=" < InputLine.txt
del InputLine.txt
echo Line read: "!line!"
goto :EOF
:TimeoutMonitor
rem Get the PID of pipe's left side
tasklist /FI "IMAGENAME eq cmd.exe" /FO TABLE /NH > tasklist.txt
for /F "tokens=2" %%a in (tasklist.txt) do (
set "leftSidePipePID=!lastButOnePID!"
set "lastButOnePID=%%a"
)
del tasklist.txt
rem Wait for the input line, or until the number of seconds passed
for /L %%i in (1,1,%2) do (
ping -n 2 localhost > NUL
if exist InputLine.txt exit /B
)
rem Timed out: kill the SET /P process and create a standard input line
taskkill /PID %leftSidePipePID% /F > NUL
echo/
echo Timed Out> InputLine.txt
exit /B
回答2:
Essentially, you can't.
You may be able to use choice
to accept a single character with timeout.
回答3:
Below there is a Batch-JScript hybrid script that achieve what you want. JScript is installed with every version of Windows from XP on. Save this file with .bat extension:
@if (@CodeSection == @Batch) @then
@echo off
rem Give the desired wait time in milliseconds:
start "" /B Cscript //nologo //E:JScript "%~F0" 10000
set "input=Time out"
set /P "input=You have 10 seconds to complete this input: "
echo Input read: %input%
goto :EOF
@end
WScript.Sleep(WScript.Arguments(0));
WScript.CreateObject("WScript.Shell").SendKeys("{ENTER}");
回答4:
If a downloadable tool is permitted, you can use editv64.exe (64-bit) or editv32.exe (32-bit) with the -t
parameter. For example:
editv64 -p "Enter something within 10 seconds: " -t 10 INP
The tool has additional advantages, such as hiding the input string when typed (-m
) as well as editing an existing environment variable interactively. You can download it here:
http://www.westmesatech.com/editv.html