PoshCode Archive  Artifact [65931950d9]

Artifact 65931950d912e1ed934d2c19341b4b3520451e5a066be6a7c627a3d69125971e:

  • File Measure-Total.ps1 — part of check-in [ef8de7028a] at 2018-06-10 12:56:17 on branch trunk — A general-purpose function for generating a “totals” row for data with numeric properties. (user: Joel Bennett size: 1849)

# encoding: ascii
# api: powershell
# title: Measure-Total
# description: A general-purpose function for generating a “totals” row for data with numeric properties.
# version: 0.1
# type: script
# author: Joel Bennett
# license: CC0
# function: measure-total
# x-poshcode-id: 1031
# x-archived: 2016-03-05T11:37:07
# x-published: 2010-04-15T12:56:00
#
#
#.Synopsis
#  Calculate sums on top of Measure-Object
#.Description
#  Pipe in objects with numerical properties, and get an extra output item
#  with the sum of all the specified properties
#.Parameter Property
#  The names of the properties to total
#.Example
#  wc *.ps1 | total words, lines
#
#  Calculates line, word, and character counts for powershell script files in the current directory, 
#  and THEN adds a total row with totals for words and lines (but not Chars)
#.Example
#  wc *.rb | total
#
#  Calculates line, word, and character counts for rubyscript files in the current directory, 
#  and THEN adds a total row with totals for ALL NUMERIC PROPERTIES ;-)

function measure-total {
PARAM([string[]]$property)
END {
   $input # output the input
   ## "Magically" figure out the numeric properties
   if(!$property) {
      $input.reset()
      $property = $input | gm -type Properties | 
         where { trap{continue} ( new-object "$(@($_.Definition -split " ")[0])" ) -as [double] -ne $null } |
         foreach { $_.Name }
      $input.reset()
   }
   $input.reset()
   # then calculate the sum of the numeric properties
   $sum = $input | measure $property -sum -erroraction 0
   # and make a new object to hold the sums
   $output = new-object PSObject
   $sum | % { Add-Member -input $output -Type NoteProperty -Name $_.Property -Value $_.Sum }
   
   $output # output the output
}}
new-alias total measure-total