Measure Statistical Properties of a List
1. Problem
You want to measure the numeric (minimum, maximum, sum, average) or textual (characters, words, lines) features of a list of objects.
2. Solution
Use the Measure-Object cmdlet to measure these statistical properties of a list.
To measure the numeric features of a stream of objects, pipe those objects to the Measure-Object cmdlet:
PS >1..10 | Measure-Object–Average -Sum
Count : 10
Average : 5.5
Sum : 55
Maximum :
Minimum :
Property :
To measure the numeric features of a specific property in a stream of objects, supply that property name to the –Property parameter of the Measure-Object cmdlet. For example, in a directory with files:
Code View: Scroll / Show All
PS >Get-ChildItem | Measure-Object -Property Length -Max -Min -Average -Sum
Count : 427
Average : 10617025.4918033
Sum : 4533469885
Maximum : 647129088
Minimum : 0
Property : Length
To measure the textual features of a stream of objects, use the –Character, -Word, and –Line parameters of the Measure-Object cmdlet:
PS >Get-ChildItem > output.txt
PS >Get-Content output.txt | Measure-Object -Character -Word -Line
Lines Words Characters Property
----- ----- ---------- --------
964 6083 33484
3. Discussion
By default, the Measure-Object cmdlet counts only the number of objects it receives. If you want to measure additional properties (such as the maximum, minimum, average, sum, characters, words, or lines) of those objects, then you need to specify them as options to the cmdlet.
For the numeric properties, though, you usually don’t want to measure the objects themselves. Instead, you probably want to measure a specific property from the list—such as the Length property of a file. For that purpose, the Measure-Object cmdlet supports the –Property parameter to which you provide the property you want to measure.
Sometimes, you might want to measure a property that isn’t a simple number—such as the LastWriteTime property of a file. Since the LastWriteTime property is a DateTime, you can’t determine its average immediately. However, if any property allows you to convert it to a number and back in a meaningful way (such as the Ticks property of a DateTime), then you can still compute its statistical properties. Example 6-2 shows how to get the average LastWriteTime from a list of files.
Example 6-2. Using the Ticks property of the DateTime class to determine the average LastWriteTime of a list of files
For more information about the Measure-Object cmdlet, type Get-HelpMeasure-Object.
Tags: get-help, info, list, measure, object, power shell, properties, result
