【发布时间】:2015-03-24 11:28:28
【问题描述】:
如何在一定时间后退出 SET /p 命令?例如,如果用户输入内容的时间过长,我想退出 SET /p。
【问题讨论】:
标签: batch-file cmd
如何在一定时间后退出 SET /p 命令?例如,如果用户输入内容的时间过长,我想退出 SET /p。
【问题讨论】:
标签: batch-file cmd
这是一个纯Batch的解决方案,避免了Batch-JScript混合脚本在使用Sendkeys且原始窗口不在焦点时出现的问题。
@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
【讨论】:
如果允许下载工具,您可以使用带有-t 参数的editv64.exe(64 位)或editv32.exe(32 位)。例如:
editv64 -p "Enter something within 10 seconds: " -t 10 INP
该工具具有其他优点,例如在键入时隐藏输入字符串 (-m) 以及以交互方式编辑现有环境变量。你可以在这里下载:
【讨论】:
下面有一个 Batch-JScript 混合脚本可以实现你想要的。从 XP 开始,每个版本的 Windows 都安装了 JScript。使用 .bat 扩展名保存此文件:
@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}");
【讨论】:
choice 或timeout 命令可能更可取。
基本上,你不能。
您可以使用choice 来接受单个字符超时。
【讨论】: