batch-file - 如何在批处理文件中退出 SET/p

标签 batch-file cmd

如何在一定时间后退出 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/

相关文章:

node.js - 带有 child_process 的 NodeJs 脚本在 Windows 上生成,为什么我需要 'shell: true' 才能出现 ENOENT 错误?

batch-file - 使用 ping.exe 的 ERRORLEVEL 测试 IP 可达性

batch-file - Windows CMD/BATCH 命令 - 显示匹配上/下行的 FC 命令

windows - 为什么这个增量不能批量工作?

batch-file - 如何使批处理文件中的命令超时?

windows - 使用 Windows 命令 shell 创建多个文件

batch-file - 如何使用延迟扩展来处理批处理脚本中的值

batch-file - Batch 无法正确计算方程

windows - 使用批处理文件读取键值对

batch-file - 如何在 QBasic 中运行批处理文件?