Home > database >  Get Average from String 00:00:00 with Powershell
Get Average from String 00:00:00 with Powershell

Time:04-20

I have some data to analyse. One example is a list of durations of tasks:

$tasks.duration

00:04:44
00:00:00
00:00:05

Is there a simple way to get the avarage duration from this list? Obviously you can't just use something like Measure-Object, because it's a string with special characters.

How would you approach this and why?

CodePudding user response:

Obviously you can't just use something like Measure-Object, because it's a string with special characters.

Parse the strings into [timespan] values, then calculate the average number of seconds in each, turn the result back into a [timespan] and then finally produce a correctly formatted string:

$measurement = $tasks.duration |ForEach-Object {
  # cast string value to [timespan], output TotalSeconds
  ([timespan]$_).TotalSeconds
} |Measure-Object -Average

# Now we can create a new string value based on the average number of seconds
$avgString = [timespan]::FromSeconds($measurement.Average).ToString('hh\:mm\:ss')

Which, with the sample values you've provided, gives:

PS ~> $avgString
00:01:36
  • Related