Paulo
Paulo

Reputation: 361

Powershell export to csv sum of timespan

I need to export to a csv file the result of a sum timespans values.

 $outItems = New-Object System.Collections.Generic.List[System.Object]

 [TimeSpan[]]$outItems = foreach ($eachtimer in $DurationColl){

 if ($eachtimer -match 'H|M|S'){
   Convert-TimeString -Time  $eachtimer -Format 'm\Ms\.fff\S' }
 else {
   Convert-TimeString -Time $eachtimer -Format "h\:mm\:ss"} 
}

 $seconds = ($outItems | Measure-Object -Property TotalMilliseconds -Sum).Sum
 $ts =  [timespan]::FromMilliseconds($seconds) 
 $ert =  ("{0:hh\:mm\:ss\,fff}" -f $ts) 
 $ert | Export-Csv  C:\Users\User\Documents\output.csv -Append -NoTypeInformation -Encoding ASCII

The $ert value is 04:05:38,631 and on csv appear the property lenght. In resume, my Export-Csv doesn't work.

Thanks for any help

Upvotes: 0

Views: 131

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

Export-Csv converts input objects into a delimited text file. The properties of those objects become the columns/headers and the values become rows that align under the columns. When your input object is a type string, the only property of a string is Length. Therefore, the result you see is expected. To achieve the expected behavior, you should use object types that contain the properties you desire or create your own custom objects.

Using custom object, you can do the following, which will create an object with property Timespan.

[pscustomobject]@{'Timespan' = $ert} |
    Export-Csv C:\Users\User\Documents\output.csv -Append -NoTypeInformation -Encoding ASCII

Upvotes: 2

Related Questions