I have a script that kicks off an event and waits for the user to press any key to stop the script execution. I was trying to find a way to show a timer (how long the script has been running) while waiting for user input at Read-Host. Is there a way to accomplish this?
This works
$Time = [System.Diagnostics.Stopwatch]::StartNew() while ($true) { $CurrentTime = $Time.Elapsed write-host $([string]::Format("`rTime: {0:d2}:{1:d2}:{2:d2}", $CurrentTime.hours, $CurrentTime.minutes, $CurrentTime.seconds)) -nonewline sleep 1 if ($Host.UI.RawUI.KeyAvailable -and ("q" -eq $Host.UI.RawUI.ReadKey("IncludeKeyUp,NoEcho").Character)) { Write-Host "Exiting now" break; } }
Use Measure-Command Cmdlet to Measure Runtime of a Script in PowerShell. Using the Measure-Command cmdlet in PowerShell is easy to measure the runtime or execution time. This command can also tell you how long a custom function or an entire script takes to execute.
Description. The Measure-Command cmdlet runs a script block or cmdlet internally, times the execution of the operation, and returns the execution time. Script blocks run by Measure-Command run in the current scope, not a child scope.
A simple function A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces. The function shown is a simple example that returns the version of PowerShell.
This gave me the output I was after :)
$StartTime = $(get-date) $elapsedTime = $(get-date) - $StartTime $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With