Measuring objects in PowerShell 3.0

April 9, 2012

one comment

The Measure-Object cmdlet gives us a great way to find minimum and maximum values in a collection of objects. For example, if we want to know the smallest and largest size of a file in the current directory:

PS> Get-ChildItem | Measure-Object -Property Length -Minimum -Maximum

Count    : 2751
Average  :
Sum      :
Maximum  : 56297240
Minimum  : 35
Property : Length

In PowerShell 2.0 it only worked with numeric properties (integers), we couldn’t use it to compare properties like LastWriteTime (DateTime). In PowerShell 3.0 we can now use the Minimum and Maximum parameters to work with anything that is IComparable. We can tell if an instance of an object is IComparable by checking if the CompareTo method exist on the instance:

PS> $object.PSObject.Methods | Where-Object {$_.Name -eq 'CompareTo'}


But there’s a simpler way using the -is operator. If we get $true – we can measure it:

PS> $object -is [IComparable]

 

In this example we measure the LastWriteTime property, which is a DateTime object. We can see the modification time of the oldest and newest files in the current directory.

PS> Get-ChildItem | Measure-Object -Property LastWriteTime -Minimum -Maximum

Count    : 2844
Average  :
Sum      :
Maximum  : 4/8/2012 8:03:32 PM
Minimum  : 9/4/2004 3:00:00 AM
Property : LastWriteTime
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

one comment

  1. JustinApril 9, 2012 ב 15:01

    great post. There are so many things i use in V3 that i just assume worked in V2!

    Reply