How to use the “-Property” parameter for PowerShell’s “Measure-Object” cmdlet?

Question:

Why does

work, when

doesn’t?

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

The second example returns this:


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:

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

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?

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:


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.

Answer:

One thing you need to know is that in PowerShell generally, and particulary in CmdLets you manipulate objects or collection of objects.

Example: if only one ‘AcroRd32’ is running Get-Process will return a [System.Diagnostics.Process], if more than one are running it will return a collection of [System.Diagnostics.Process].

In the second case you can write:


Because a collection has a count property. The duality object collection is also valid in CmdLets parameters that most of the time supports objects or list of objects (collection built with the operator ,).

Just use the Get-Member cmdlet:

And

Source:

How to use the “-Property” parameter for PowerShell’s “Measure-Object” cmdlet? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply