Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for user input with a timeout

Tags:

I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.

EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.

function Pause-Host {     param(             $Delay = 1          )     $counter = 0;     While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))     {         [Threading.Thread]::Sleep(1000)     } } 
like image 625
EBGreen Avatar asked Sep 29 '08 19:09

EBGreen


2 Answers

Found something here:

$counter = 0 while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600)) {       [Threading.Thread]::Sleep( 1000 ) } 
like image 180
Lars Truijens Avatar answered Sep 28 '22 08:09

Lars Truijens


It's quite old now but how I solved it based on the same KeyAvailable method is here:

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

It waits for x seconds, displaying a . for each second that elapses up to the maximum wait time. If a key is pressed it returns $true, otherwise $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; } 

And to use:

$val = TimedPrompt "Press key to cancel restore; will begin in 3 seconds" 3 Write-Host $val 
like image 29
nathanchere Avatar answered Sep 28 '22 08:09

nathanchere