首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >等待用户输入并超时

等待用户输入并超时
EN

Stack Overflow用户
提问于 2008-09-29 19:05:48
回答 6查看 23.2K关注 0票数 25

我已经搜索过了,但显然我的google foo很弱。我需要的是一种在控制台中提示用户输入的方法,并在一段时间后让请求超时,如果没有输入,则继续执行脚本。据我所知,Read-Host不提供此功能。$host.UI.PromptForChoice()和$host.UI.RawUI.ReadKey()都不需要。提前感谢您的指点。

编辑:非常感谢Lars Truijens找到了答案。我已经将他指出的代码封装到一个函数中。请注意,我实现它的方式意味着在用户点击某个键和脚本继续执行之间可能会有长达一秒的延迟。

function Pause-Host
{
    param(
            $Delay = 1
         )
    $counter = 0;
    While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))
    {
        [Threading.Thread]::Sleep(1000)
    }
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2008-09-29 19:44:48

我发现了一些here

$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
      [Threading.Thread]::Sleep( 1000 )
}
票数 19
EN

Stack Overflow用户

发布于 2015-03-30 18:00:49

它现在已经很老了,但我是如何基于相同的KeyAvailable方法解决它的:

https://gist.github.com/nathanchere/704920a4a43f06f4f0d2

它等待x秒,显示达到最大等待时间的每秒的.。如果按下某个键,则返回$true,否则返回$false

Function TimedPrompt($prompt,$secondsToWait){   
    Write-Host -NoNewline $prompt
    $secondsCounter = 0
    $subCounter = 0
    While ( (!$host.ui.rawui.KeyAvailable) -and ($count -lt $secondsToWait) ){
        start-sleep -m 10
        $subCounter = $subCounter + 10
        if($subCounter -eq 1000)
        {
            $secondsCounter++
            $subCounter = 0
            Write-Host -NoNewline "."
        }       
        If ($secondsCounter -eq $secondsToWait) { 
            Write-Host "`r`n"
            return $false;
        }
    }
    Write-Host "`r`n"
    return $true;
}

并使用:

$val = TimedPrompt "Press key to cancel restore; will begin in 3 seconds" 3
Write-Host $val
票数 6
EN

Stack Overflow用户

发布于 2018-05-10 21:47:52

对于那些正在寻找现代解决方案的人来说,以下解决方案可能会对您有所帮助:

Write-Host ("PowerShell Script to run a loop and exit on pressing 'q'!")
$count=0
$sleepTimer=500 #in milliseconds
$QuitKey=81 #Character code for 'q' key.
while($count -le 100)
{
    if($host.UI.RawUI.KeyAvailable) {
        $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp")
        if($key.VirtualKeyCode -eq $QuitKey) {
            #For Key Combination: eg., press 'LeftCtrl + q' to quit.
            #Use condition: (($key.VirtualKeyCode -eq $Qkey) -and ($key.ControlKeyState -match "LeftCtrlPressed"))
            Write-Host -ForegroundColor Yellow ("'q' is pressed! Stopping the script now.")
            break
        }
    }
    #Do your operations
    $count++
    Write-Host ("Count Incremented to - {0}" -f $count)
    Write-Host ("Press 'q' to stop the script!")
    Start-Sleep -m $sleepTimer
}
Write-Host -ForegroundColor Green ("The script has stopped.")

示例脚本输出:

有关处理更多组合的信息,请参阅有关键状态的Microsoft document

致词:Technet Link

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/150161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档