Search code examples
powershellkeypressdo-loops

Exit Do-Until Loop with any key


I want to create a simple loop until user presses any key. The goal is that the loops stop only if any key is pressed. Otherwise loop and loop and loop without any interaction. I think my code will tell you what I'am want. But I am not sure if this solveable with this type of loop?

$sec = 0
Write-Host 'Press any key to quit...'

do {
    Write-Host -ForegroundColor Green "$sec Sec"
    Start-Sleep -Seconds 1
    $sec ++    
} until ($null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown'))

Solution

  • You can use [System.Console]::KeyAvailable. It will return a value, once a key press is available in the input stream.

    $sec = 0 
    do 
    {
        Write-Host -ForegroundColor Green "$sec Sec"
        Start-Sleep -Seconds 1
        $sec++    
    
    } until ([System.Console]::KeyAvailable)
    

    Once you press any key, this will end the loop as soon as the loop condition is evaluated.