Skip to content

Instantly share code, notes, and snippets.

@PanosGreg
Created December 26, 2024 12:05
Show Gist options
  • Save PanosGreg/3c677a2063527015b08feaaba616185a to your computer and use it in GitHub Desktop.
Save PanosGreg/3c677a2063527015b08feaaba616185a to your computer and use it in GitHub Desktop.
Get the elapsed duration as a string
function Get-DurationText {
<#
.SYNOPSIS
Get the elapsed duration as a string, in a number of different formats
.EXAMPLE
Get-DurationText -Duration ([timespan]::FromDays(2))
2d 0hr
#>
[CmdletBinding(DefaultParameterSetName='Timespan')]
[OutputType([string])]
param (
[Parameter(Mandatory,Position=0,ValueFromPipeline,ParameterSetName='Stopwatch')]
[System.Diagnostics.Stopwatch]$Timer,
[Parameter(Mandatory,Position=0,ValueFromPipeline,ParameterSetName='Timespan')]
[System.Timespan]$Duration,
[Parameter(Mandatory,Position=0,ValueFromPipeline,ParameterSetName='Datetime')]
[ValidateScript({(Get-Date) -ge $_})] # <-- make sure the provided date is in the past, as-in it's older than now
[datetime]$Date,
[Parameter(Position=1)]
[ValidateSet('WithLetter','WithColon','WithSpace')]
[string]$TimeFormat = 'WithSpace'
)
if ($PSCmdlet.ParameterSetName -eq 'Stopwatch') {
$Timer.Stop()
$Timespan = $Timer.Elapsed
}
elseif ($PSCmdlet.ParameterSetName -eq 'Datetime') {
$Timespan = (Get-Date) - $Date
}
else {$Timespan = $Duration}
# generate the various formats for the duration
if ($Timespan.TotalDays -ge 5) {$fmt1 = 'dd\dhh' ; $fmt2 = 'd\dh\h' ; $fmt3 = 'd\d'}
elseif ($Timespan.TotalDays -ge 1) {$fmt1 = 'dd\dhh\:mm' ; $fmt2 = 'd\dh\h' ; $fmt3 = 'd\d\ h\h\r'}
elseif ($Timespan.TotalHours -ge 9) {$fmt1 = 'hh\:mm\:ss' ; $fmt2 = 'h\hm\m' ; $fmt3 = 'h\h\r\'}
elseif ($Timespan.TotalHours -ge 1) {$fmt1 = 'hh\:mm\:ss' ; $fmt2 = 'h\hm\m' ; $fmt3 = 'h\h\r\ m\m\i\n'}
elseif ($Timespan.TotalMinutes -ge 9) {$fmt1 = 'mm\:ss' ; $fmt2 = 'm\ms\s' ; $fmt3 = 'm\m\i\n'}
elseif ($Timespan.TotalMinutes -ge 1) {$fmt1 = 'mm\:ss' ; $fmt2 = 'm\ms\s' ; $fmt3 = 'm\m\i\n\ s\s\e\c'}
elseif ($Timespan.TotalSeconds -ge 9) {$fmt1 = 'ss\.fff' ; $fmt2 = 's\sfff\m\s' ; $fmt3 = 's\s\e\c'}
elseif ($Timespan.TotalSeconds -ge 1) {$fmt1 = 'ss\.fff' ; $fmt2 = 's\sfff\m\s' ; $fmt3 = 's\s\e\c\ fff\m\s'}
else {$fmt1 = 'fff' ; $fmt2 = 'fff\m\s' ; $fmt3 = 'fff\m\s'}
switch ($TimeFormat) {
'WithColon' {$out = $Timespan.ToString($fmt1)} # ex. 02:12
'WithLetter' {$out = $Timespan.ToString($fmt2).TrimStart('0')} # ex. 2m12s
'WithSpace' {$out = $Timespan.ToString($fmt3)} # ex. 2min 12sec
default {$out = $Timespan.ToString()} # ex. 00:02:12.0708419
}
Write-Output $out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment