PowerShell – Measure-Object cmdlet

In this Article, we will discuss about Measure-Object cmdlet.

The Measure-Object cmdlet

Another interesting command PowerShell provides is Measure-Object; which is useful to measure the numeric properties of the object, like files count in the given directory, number of lines in the given file etc,.

This command needs always an input. Hence we can not use this command directly; we use it in pipeline only. That means, the output of another command will be the input of this command to measure the numeric properties of the objects.

If you call without an input; you will see no details. Here it is:

PS C:\> Measure-Object

Count : 0
Average :
Sum :
Maximum :
Minimum :
Property :

Observe that, it displays all the numeric properties; any by default it display the count of objects. As we didn’t pass any input to it, it displays the count as 0.

Let’s take an example, which will display number of files (including directories) in the current directory. Here is the command:

PS C:\> Get-ChildItem | Measure-Object

Count : 51
Average :
Sum :
Maximum :
Minimum :
Property :

From above result, numeric property Count displays the number of files and directories available in the current directory. What about other numeric properties? To display, we have to pass them as an argument. For example, the property Maximum display the largest value; here, largest file size. You need to pass it as an argument like below:

PS C:\> Get-ChildItem | Measure-Object -Maximum
Measure-Object : Cannot compare "AIP" because it is not IComparable.
At line:1 char:17
+ Get-ChildItem | Measure-Object -Maximum
+                 ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Measure-Object], PSArgumentException
    + FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.MeasureObjectCommand

Why it was showing the Error? This is because the input what we are passing and the parameter are NOT comparable. Input is the collection of files and folders; and we are requesting for the Maximum value. This is NOT clear instruction to the command. Hence showing an Error.

To fix the above Error, we need to clearly instruct to the command compare with size of the file to find the maximum value. How do we pass this? It is simple. Get-ChildItem will display the list of files and folders with the size of the file. We will get the size of the file through Length property. We will pass this as an argument to Measure-Object cmdlet. Here is the command:

PS C:\> Get-ChildItem | Measure-Object -Maximum Length

Count : 33
Average :
Sum :
Maximum : 1442522
Minimum :
Property : Length

Observe that, it displays the count of the files (excluding directories) and shows the maximum size of the file.

We will discuss more PowerShell topics in my upcoming Articles.

[..] David

PowerShell – Measure-Object cmdlet

Leave a Reply

Your email address will not be published.

Scroll to top