发现了一些在这里:
$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