Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format timer.elapsed for write-host

$timer = [System.Diagnostics.Stopwatch]::StartNew()
Start-Sleep -Second 83
$timer.stop
$elapsed=$timer.elapsed
Write-Host $elapsed                                 < Works, but not shown in desired format
Write-Host $elapsed.ToString("DD:HH:MM:SS")         < Overload error on .ToString and Argument count:"1"
Write-Host $($elapsed).ToString("DD:HH:MM:SS")      < Overload error on .ToString and Argument count:"1"

I cannot get the elapsed time to output in the desired format ("DD:HH:MM:SS"; 2 digit days, hours, minutes and seconds). I've found quite a bit about formatting dates/times directly from Get-Date, and some even claim to show or calculate differences between a start and end time. But I keep getting Overload errors on any attempt to enforce formatting.

like image 693
NewbieBAT Avatar asked Feb 07 '26 21:02

NewbieBAT


1 Answers

The format strings for a TimeSpan are a bit different from the format strings of DateTime. See Custom TimeSpan format strings.

The format string is all lower case and requires escaping on ::

$timer.Elapsed.ToString('dd\:hh\:mm\:ss')

As an aside, $timer.Stop will get you the method overload definitions; if you want to invoke the method, you have to add () to it:

$timer.Stop()
like image 99
Santiago Squarzon Avatar answered Feb 09 '26 10:02

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!