我搜索过,但显然我的谷歌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)
}
}
答案 0 :(得分:16)
发现了一些here:
$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
[Threading.Thread]::Sleep( 1000 )
}
答案 1 :(得分:5)
现在已经很老了,但我是如何基于相同的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
答案 2 :(得分:1)
对于正在寻找具有额外约束的现代解决方案的用户,可以在预定义的按键上退出PowerShell脚本,以下解决方案可能对您有所帮助:
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 :(得分:0)
这是一个按键实用程序函数,它接受:
只有匹配的按键才会反映在屏幕上。
用法:
$key = GetKeyPress '[ynq]' "Run step X ([y]/n/q)?" 5
if ($key -eq $null)
{
Write-Host "No key was pressed.";
}
else
{
Write-Host "The key was '$($key)'."
}
实施:
Function GetKeyPress([string]$regexPattern='[ynq]', [string]$message=$null, [int]$timeOutSeconds=0)
{
$key = $null
$Host.UI.RawUI.FlushInputBuffer()
if (![string]::IsNullOrEmpty($message))
{
Write-Host -NoNewLine $message
}
$counter = $timeOutSeconds * 1000 / 250
while($key -eq $null -and ($timeOutSeconds -eq 0 -or $counter-- -gt 0))
{
if (($timeOutSeconds -eq 0) -or $Host.UI.RawUI.KeyAvailable)
{
$key_ = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp")
if ($key_.KeyDown -and $key_.Character -match $regexPattern)
{
$key = $key_
}
}
else
{
Start-Sleep -m 250 # Milliseconds
}
}
if (-not ($key -eq $null))
{
Write-Host -NoNewLine "$($key.Character)"
}
if (![string]::IsNullOrEmpty($message))
{
Write-Host "" # newline
}
return $(if ($key -eq $null) {$null} else {$key.Character})
}
答案 4 :(得分:0)
function ReadKeyWithDefault($prompt, $defaultKey, [int]$timeoutInSecond = 5 ) {
$counter = $timeoutInSecond * 10
do{
$remainingSeconds = [math]::floor($counter / 10)
Write-Host "`r$prompt (default $defaultKey in $remainingSeconds seconds): " -NoNewline
if($Host.UI.RawUI.KeyAvailable){
$key = $host.UI.RawUI.ReadKey("IncludeKeyUp")
Write-Host
return $key
}
Start-Sleep -Milliseconds 100
}while($counter-- -gt 0)
Write-Host $defaultKey
return $defaultKey
}
$readKey = ReadKeyWithDefault "If error auto exit( y/n )" 'y' 5
答案 5 :(得分:0)
timeout.exe 5
仍然可以在 powershell 中工作。等待 5 秒或直到按键。
也许不优雅。不过很简单。
然而,
它从 Powershell_ISE 弹出一个新的命令提示符窗口,并立即返回,因此它不会等待(从 Powershell 控制台它使用该控制台并等待)。您可以通过多一点工作让它从 ISE 等待(仍然会弹出自己的窗口):
if ($psISE) {
start -Wait timeout.exe 5
} else {
timeout.exe 5
}