等待用户输入超时 [英] Waiting for user input with a timeout

查看:51
本文介绍了等待用户输入超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索过,但显然我的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆