如何在一定时间后退出 SET/p 命令?例如,如果用户输入内容的时间太长,我想退出 SET/p。
最佳答案
这是一个纯 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
关于batch-file - 如何在批处理文件中退出 SET/p,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143549/