Is there a direct way to handle the “duration” in powershell. For example, I have the below three duration and I would like to add them and get the result as a timespan object so that I can get the totalminutes or totalseconds etc.
That’s off the top of my head, so it might not be 100% accurate, but that’s the idea.
Once you have a Timespan, you can add or subtract others. A ToString() method of the Timespan lets you turn the Timespan into a readable string format.
Well, your $a, $b and $c variables are currently strings. You would need to have Timespan objects first, at which point they can simply be added together with the + operator. Whether you need to convert strings into timespans or just start with a timespan depends on what you’re doing; I’ll show examples of both here:
# Converting from strings. Note that the colon character is escaped with a backslash in the patterns.
# Casting to [string[]] is necessary here to make sure the right overload of TimeSpan.ParseExact gets called.
[string[]] $patterns = @(
'mm\:ss'
'h\:mm\:ss'
'hh\:mm\:ss'
)
$a = [timespan]::ParseExact('1:02:48', $patterns, [cultureinfo]::CurrentCulture)
$b = [timespan]::ParseExact('21:38', $patterns, [cultureinfo]::CurrentCulture)
$c = [timespan]::ParseExact('44:21', $patterns, [cultureinfo]::CurrentCulture)
$total = $a + $b + $c
$total
# Using New-Timespan instead of bothering with strings. Less fragile and less annoying. :)
$a = New-TimeSpan -Hours 1 -Minutes 2 -Seconds 48
$b = New-TimeSpan -Minutes 21 -Seconds 38
$c = New-TimeSpan -Minutes 44 -Seconds 21
$total = $a + $b + $c
$total