1

There is a hashtable of view: key(string) - value (dateTime)

Have to find the min value among Values (dateTime-s). Can't find generic method to find such a value. The only way is smth like

$first_file_date = $dates_hash.Values | Measure-Object -Minimum -Maximum
Get-Date ($first_file_date);

Though visibly I get the result ($first_file_date) the actual value casts to GenericObjectMeasureInfo type and I can't cast it back to DateTime to work further.

Any ideas?

mklement0
  • 382,024
  • 64
  • 607
  • 775
blackraven
  • 33
  • 3

3 Answers3

2

The value you're interested in is stored in the Minimum and Maximum properties of the object returned by Measure-Object:

$measurement = $dates_hash.Values | Measure-Object -Minimum -Maximum

# Minimum/oldest datetime value is stored here
$measurement.Minimum

# Maximum/newest datetime value is stored here
$measurement.Maximum

Use ForEach-Object or Select-Object if you want the raw value in a single pipeline:

$oldest = $dates_hash.Values | Measure-Object -Minimum | ForEach-Object -MemberName Minimum
# or 
$oldest = $dates_hash.Values | Measure-Object -Minimum | Select-Object -ExpandProperty Minimum
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

To complement Mathias R. Jessen's helpful answer with an alternative solution based on LINQ:

# Sample hashtable.
$hash = @{
  foo = (Get-Date)
  bar = (Get-Date).AddDays(-1)
}

# Note that the minimum is sought among the hash's *values* ([datetime] instances)
# The [datetime[] cast is required to find the appropriate generic overload.
[Linq.Enumerable]::Min([datetime[]] $hash.Values)

Use of LINQ from PowerShell is generally cumbersome, unfortunately (see this answer). GitHub proposal #2226 proposes improvements.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Just use Sort-Object for this:

$dates_hash = @{
    "a" = (Get-Date).AddMinutes(4)    
    "b" = (Get-Date).AddMinutes(5)    
    "c" = (Get-Date).AddMinutes(2)    
    "d" = (Get-Date).AddMinutes(5)    
    "e" = (Get-Date).AddMinutes(1)    
    "f" = (Get-Date).AddMinutes(6)    
    "g" = (Get-Date).AddMinutes(8)    
}

$first_file_date = $dates_hash.Values | Sort-Object | Select-Object -First 1

Or if you want the whole object:

$first_file = $dates_hash.GetEnumerator() | Sort-Object -Property "Value" | Select-Object -First 1
mhu
  • 17,720
  • 10
  • 62
  • 93
  • `Sort-Object -Property Value` is a nice workaround for when you want to preserve the whole hashtable entry, but I wouldn't recommend `Sort-Object` for determining a minimum / maximum in general, given that it involves a lot of unnecessary work and requires building up a sorted copy of the input collection in memory. As an aside: PowerShell (Core) 7+ now allows you to use `-Top 1` with `Sort-Object` (instead of a separate `Select-Object -First 1` call). – mklement0 Jul 21 '21 at 14:16