等待用户输入超时 [英] Waiting for user input with a timeout
问题描述
我已经搜索过,但显然我的 google foo 很弱.我需要的是一种在控制台中提示用户输入并在一段时间后请求超时并在没有输入时继续执行脚本的方法.据我所知,Read-Host 不提供此功能功能.$host.UI.PromptForChoice() 和 $host.UI.RawUI.ReadKey() 都没有.提前感谢您的指点.
非常感谢 Lars Truijens 找到答案.我把他指出的代码,封装成一个函数.请注意,我实现它的方式意味着在用户按下键和脚本继续执行之间可能会有长达一秒的延迟.
函数暂停主机{参数($延迟 = 1)$计数器= 0;While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay)){[Threading.Thread]::睡眠(1000)}}
一个>:
$counter = 0while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600)){[Threading.Thread]::睡眠(1000)}
I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.
EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.
function Pause-Host
{
param(
$Delay = 1
)
$counter = 0;
While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))
{
[Threading.Thread]::Sleep(1000)
}
}
Found something here:
$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
[Threading.Thread]::Sleep( 1000 )
}
这篇关于等待用户输入超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!