Return object from array with highest value

I want to return an object from an array whose property has the highest value. I am currently doing the following

Get-VM | Sort-Object -Property ProvisionedSpaceGB | Select-Object -Last 1 

It works, but is inefficient. I don't need the whole sorted array, I just need the object with the highest value. Ideally, I would use something like

 Get-VM | Measure-Object -Property ProvisionedSpaceGB -Maximum 

but this returns the value of the property of the object, not the entire object. Is there a way for a dimension object to return a base object?

+7
powershell
source share
2 answers

Not directly. Measure-Object are an easy way to capture such values, not their input objects. You can get the most out of Measure-Object and then compare with the array, but this takes a few steps:

 $array = Get-VM $max = ($array | measure-object -Property ProvisionedSpaceGB -maximum).maximum $array | ? { $_.ProvisionedSpaceGB -eq $max} 

You can also abort the Measure-Object completely and iterate over the set, replacing the maximum and output data as you go.

 $max = 0 $array | Foreach-Object { if($max -le $_.ProvisionedSpaceGB) { $output = $_ $max = $_.ProvisionedSpaceGB } } $output 

It is a little messier to always return a single value. This will require minor adjustments if you must reuse it in case there may be several values ​​having the same maximum (for example, file size when using Get-ChildItem). It will replace $output last iteration when two or more objects have the same value for ProvisionedSpaceGB . You can turn $output into a collection easy enough to fix it.

I prefer the first solution myself, but I wanted to suggest another way to think about the problem.

+9
source share

You can use this:

 $array = Get-VM | Sort-Object -Property ProvisionedSpaceGB -Descending $array[0] 
+3
source share

All Articles