Skip to content

Instantly share code, notes, and snippets.

@adbertram
Created September 7, 2023 20:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adbertram/6646cd7531bd5d1f7c667c152aba0495 to your computer and use it in GitHub Desktop.
Save adbertram/6646cd7531bd5d1f7c667c152aba0495 to your computer and use it in GitHub Desktop.
PowerShell Timer with Real-Time Counting
# Initialize timer variables
$timerStart = $null
$elapsedTime = $null
# Function to display elapsed time
function DisplayElapsedTime {
param (
[ref]$startTime,
[ref]$elapsedTime
)
while ($true) {
# Calculate and display the elapsed time
$elapsed = (Get-Date) - $startTime.Value
Write-Host -NoNewline "`rElapsed Time: $($elapsed.TotalSeconds) seconds"
# Exit loop if a key is pressed
if ($host.UI.RawUI.KeyAvailable) {
$host.UI.RawUI.FlushInputBuffer()
Write-Host "" # Move to a new line
$elapsedTime.Value = $elapsed
break
}
Start-Sleep -Milliseconds 100
}
}
# Main loop to keep the script running
while ($true) {
# Get user command
$userCommand = Read-Host "Enter command (start, view, reset, exit)"
switch ($userCommand) {
"start" {
# Record the current time when the timer starts
$timerStart = Get-Date
Write-Host "Timer started. Press any key to stop."
DisplayElapsedTime -startTime ([ref]$timerStart) -elapsedTime ([ref]$elapsedTime)
}
"view" {
if ($elapsedTime -ne $null) {
Write-Host "Final Elapsed Time: $($elapsedTime.TotalSeconds) seconds"
}
else {
Write-Host "Please start the timer first."
}
}
"reset" {
# Reset all timer variables
$timerStart = $null
$elapsedTime = $null
Write-Host "Timer reset."
}
"exit" {
# Exit the script
Write-Host "Exiting script."
return
}
default {
Write-Host "Invalid command. Use start, view, reset, or exit."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment