等待超时的用户输入
问题描述:
我已经搜索,但显然我的谷歌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)
}
}
答
找到东西here:
$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
[Threading.Thread]::Sleep(1000)
}
答
现在是很老,但我如何解决它基于同样的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
非常感谢你。我在你强大的谷歌之前鞠躬。 – EBGreen 2008-09-29 19:50:35
在PowerShell 2中,还有`Start-Sleep` cmdlet。 – Joey 2011-04-06 16:27:15