Waiting for user input with a timeout

后端 未结 4 1429
北海茫月
北海茫月 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:19

    Here is a keystroke utility function that accepts:

    • Validation character set (as a 1-character regex).
    • Optional message
    • Optional timeout in seconds

    Only matching keystrokes are reflected to the screen.

    Usage:

    $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)'."
    }
    

    Implementation:

    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})
    }
    

提交回复
热议问题