Mathias R. Jessen's helpful answer shows elegant - but potentially wasteful in terms of memory - solutions (Sort-Object
of necessity needs to collect all input objects in memory so as to be able to determine the sort order).
Your own, Measure-Object
-based approach takes advantage of the memory-throttling property of the pipeline.
Due to use of PowerShell's pipeline, both approaches are likely to be slow, however - see this answer for a discussion.
A simple optimization of your approach is to make the ForEach-Object value
pipeline segment unnecessary by passing -Property value
to Measure-Object
:
$CustomObjects | Measure-Object -Property value -Minimum -Maximum
The Microsoft.PowerShell.Commands.GenericMeasureInfo
returned by this command has .Minimum
and .Maximum
properties, so there's no strict reason to create separate $min
and $max
variables, but if you wanted to:
$measureResult = $CustomObjects | Measure-Object -Property value -Minimum -Maximum
$min, $max = $measureResult.Minimum, $measureResult.Maximum
If you'd rather not create an auxiliary variable, you can use the following, which uses the .ForEach()
array method:
$min, $max = ($CustomObjects | Measure-Object -Property value -Minimum -Maximum).
ForEach({ $_.Minimum, $_.Maximum })