DCSIMG
Measuring objects in PowerShell 3.0 - Shay Levy

Shay Levy

If you repeat it, PowerShell it!

News


btn_donate_LG

View Shay Levy's profile on LinkedIn Follow Shay Levy at Twitter Shay Levy's Facebook profile Subscribe to my FriendFeed


site statistics




Measuring objects in PowerShell 3.0

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

Comments

Justin said:

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

# April 9, 2012 3:01 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: