我已经搜索过了,但显然我的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)
}
}
发布于 2008-09-29 19:44:48
我发现了一些here
$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
[Threading.Thread]::Sleep( 1000 )
}
发布于 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
发布于 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
https://stackoverflow.com/questions/150161
复制相似问题