Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the "-Property" parameter for PowerShell's "Measure-Object" cmdlet?

Why does

$a = GPS AcroRd32 | Measure
$a.Count

work, when

GPS AcroRd32 | Measure -Property Count

doesn't?

The first example returns a value of 2, which is what I want, an integer.

The second example returns this:

Measure-Object : Property "Count" cannot be found in any object(s) input.
At line:1 char:23
+ GPS AcroRd32 | Measure <<<<  -Property Count
    + CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException
    + FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand



This Scripting Guy entry is where I learned how to use the "Count" Property in the first code sample.

The second code sample is really confusing. In this Script Center reference, the following statement works:

Import-Csv c:\scripts\test.txt | Measure-Object score -ave -max -min

It still works even if it's re-written like so:

Import-Csv c:\scripts\test.txt | Measure-Object -ave -max -min -property score

I don't have too many problems with accepting this until I consider the Measure-Object help page. The parameter definition for -Property <string[]> states:

The default is the Count (Length) property of the object.

If Count is the default, then shouldn't an explicit pass of Count work?

GPS AcroRd32 | Measure -Property Count # Fails

The following provides me the information I need, except it doesn't provide me with an integer to perform operations on, as you'll see:

PS C:\Users\Me> $a = GPS AcroRd32 | Measure
PS C:\Users\Me> $a

Count    : 2
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

PS C:\Users\Me> $a -is [int]
False



So, why does Dot Notation ($a.count) work, but not an explicitly written statement (GPS | Measure -Property Count)?

If I'm supposed to use Dot Notation, then I will, but I'd like to take this opportunity to learn more about how and *why PowerShell works this way, rather than just building a perfunctory understanding of PowerShell's syntax. To put it another way, I want to avoid turning into a Cargo Cult Programmer/ Code Monkey.

like image 282
Stisfa Avatar asked Sep 30 '11 18:09

Stisfa


1 Answers

Because the COUNT property is a property of the OUTPUT object (i.e. results of Measure-Object), not the INPUT object.

The -property parameter specifies which property(ies) of the input objects are to be evaluated. None of these is COUNT unless you pass an array or arrays or something.

like image 82
JNK Avatar answered Jan 04 '23 19:01

JNK