Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell show elapsed time

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;     } } 
like image 618
Jeff Avatar asked Jun 08 '12 00:06

Jeff


People also ask

How do I count time in PowerShell?

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.

What is Measure-command in PowerShell?

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.

How do you write a function in PowerShell?

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.


1 Answers

This gave me the output I was after :)

$StartTime = $(get-date)  $elapsedTime = $(get-date) - $StartTime  $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks) 
like image 194
m0del101 Avatar answered Oct 17 '22 12:10

m0del101