【问题标题】:Find the min element of Hashtable (Values are - DateTime) on PowerShell在 PowerShell 上查找 Hashtable 的最小元素(值是 - 日期时间)
【发布时间】:2021-09-28 21:31:12
【问题描述】:

有一个哈希表的视图: 键(字符串)- 值(日期时间)

必须在 Values (dateTime-s) 中找到最小值。 找不到通用方法来找到这样的值。唯一的办法就是喜欢

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

虽然我明显得到了结果 ($first_file_date),但实际值转换为 GenericObjectMeasureInfo 类型,我无法将其转换回 DateTime 以进一步工作。

有什么想法吗?

【问题讨论】:

  • 你想要日期时间值还是对应的字符串?
  • 请允许我给你一个标准的建议给新手:如果你accept 一个答案,你将帮助未来的读者,向他们展示解决了你的问题的方法。要接受答案,请单击答案左侧大数字下方的大 ✓ 符号(您将获得 2 点声望)。如果您至少有 15 个声望点,您还可以投票给其他有用的答案(也可以选择接受的答案)。如果您的问题尚未解决,请提供反馈,或者,如果您自己找到了解决方案,请self-answer

标签: powershell hashtable


【解决方案1】:

您感兴趣的值存储在Measure-Object返回的对象的MinimumMaximum属性中:

$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

如果您想在单个管道中获取原始值,请使用 ForEach-ObjectSelect-Object

$oldest = $dates_hash.Values | Measure-Object -Minimum | ForEach-Object -MemberName Minimum
# or 
$oldest = $dates_hash.Values | Measure-Object -Minimum | Select-Object -ExpandProperty Minimum

【讨论】:

    【解决方案2】:

    用基于 LINQ 的替代解决方案来补充 Mathias R. Jessen's helpful answer

    # 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)
    

    不幸的是,在 PowerShell 中使用LINQ 通常很麻烦(请参阅this answer)。 GitHub proposal #2226 提出改进建议。

    【讨论】:

      【解决方案3】:

      只需使用 Sort-Object 即可:

      $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
      

      或者如果你想要整个对象:

      $first_file = $dates_hash.GetEnumerator() | Sort-Object -Property "Value" | Select-Object -First 1
      

      【讨论】:

      • Sort-Object -Property Value 是一个很好的解决方法,当您想要保留整个哈希表条目时,但我不建议使用Sort-Object 来确定一般的最小值/最大值,因为它涉及很多不必要的工作,并且需要在内存中建立输入集合的排序副本。顺便说一句:PowerShell (Core) 7+ 现在允许您将 -Top 1Sort-Object 一起使用(而不是单独的 Select-Object -First 1 调用)。
      猜你喜欢
      • 2021-08-05
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      相关资源
      最近更新 更多