Skip to content

Instantly share code, notes, and snippets.

@asheroto
Last active August 6, 2024 08:36
Show Gist options
  • Save asheroto/7be9d7c945a09d82bca86df75e9a9d7a to your computer and use it in GitHub Desktop.
Save asheroto/7be9d7c945a09d82bca86df75e9a9d7a to your computer and use it in GitHub Desktop.
PowerShell script to wait for a key press or countdown from a specified timeout with in-place countdown display.
Function Wait-ForKeyOrTimeout {
param (
[int]$Timeout = 10
)
for ($i = $Timeout; $i -ge 0; $i--) {
Write-Host -NoNewline "`rPress any key to close... (Closing in $i seconds) "
if ([System.Console]::KeyAvailable) {
[void][System.Console]::ReadKey($true)
Write-Host "`rKey pressed, exiting countdown... " # Clear line with spaces
return
}
Start-Sleep -Seconds 1
}
Write-Host "`rPress any key to close... (Closing in 0 seconds) " # Clear the last countdown
}
# Example usage
Wait-ForKeyOrTimeout -Timeout 10

Wait for Key or Timeout

This PowerShell script waits for a key press or counts down from a specified timeout, displaying the countdown in-place. If a key is pressed during the countdown, the script exits immediately.

Wait-ForKeyOrTimeout.ps1.mp4

Usage

Wait-ForKeyOrTimeout -Timeout 10

This will display a message counting down from 10 seconds, updating in-place, and will exit immediately if a key is pressed during the countdown.

Parameters

  • Timeout: The number of seconds to count down from (default is 10).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment