Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get Average from String 00:00:00 with Powershell

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading