Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear $host.UI.RawUI.KeyAvailable

Tags:

powershell

I have a script that auto-refreshes every 30 minutes and upon bringing the console window to focus and pressing any key, it will refresh manually. The problem is that once you press a key, it stops auto-refreshing.

$timeout = New-TimeSpan -Minutes 30    
$sw = [diagnostics.stopwatch]::StartNew()

while ($sw.elapsed -lt $timeout){
    if ($host.UI.RawUI.KeyAvailable) {
        $key = $host.UI.RawUI.ReadKey() 
        break 
    }
    start-sleep -seconds 5          
}  

The problem is the 4th line of text. Once you press a key and it gets stored in $host.UI.RawUI.KeyAvailable, it seems to retain that after the whole thing loops and it thinks you pressed another key again when you didn't, so it will not go back to the auto-refreshing every 30 minutes. Is it possible to clear out $host.UI.RawUI.KeyAvailable ?

like image 868
Aaron Avatar asked Oct 24 '25 20:10

Aaron


1 Answers

Solved it myself by focusing on the key after it is pressed.

$timeout = New-TimeSpan -Minutes $sleepmin
$sw = [diagnostics.stopwatch]::StartNew()

while ($sw.Elapsed -lt $timeout){
        if ($host.UI.RawUI.KeyAvailable) {
            $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp,IncludeKeyDown")
            if ($key.KeyDown -eq "True"){
                        break    
                        }           
            } 
Start-Sleep -Seconds 5
     }  
like image 114
Aaron Avatar answered Oct 26 '25 11:10

Aaron