Search code examples
.netpowershellpowershell-7

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.


Solution

  • 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()