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

use*_*711 3 cmd batch-file

如何在一段时间后退出 SET /p 命令?例如,如果用户输入的时间太长,我想退出 SET /p。

Aac*_*ini 5

这是一个纯粹的 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
Run Code Online (Sandbox Code Playgroud)

  • @BILL 在脚本上发出 sed 's/InputLine.txt/"%TMP%"\\InputLine.txt/g' 就解决了,对,假设用户对 %TMP% 具有写访问权限,否则将 %TMP% 替换为任何你想要的路径,只要你使用 sed 来搜索/替换,你就必须用 '\\' 转义 \。另一种选择是在 notepad.exe 中打开文件并进行搜索和替换。搜索:InputLine.txt 替换:"&lt;somePathTheUserCanWriteTo&gt;"\InputLine.txt 这些是 Aacini 无法猜测的环境问题,通常很容易解决;你必须承认,他做了最难的部分。 (2认同)