Waiting for user input with a timeout

后端 未结 4 1433
北海茫月
北海茫月 2020-11-28 15:36

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 c

4条回答
  •  天命终不由人
    2020-11-28 16:12

    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
    

提交回复
热议问题