【问题标题】:Loop through dates in hash table?遍历哈希表中的日期?
【发布时间】:2016-11-09 19:07:22
【问题描述】:

我在 Powershell 中有一个如下所示的哈希表 ($hash_dates.GetEnumerator() | sort -Property name):

11/1/2016 12:00:00 AM          5
11/2/2016 12:00:00 AM          3
11/4/2016 12:00:00 AM          2

密钥的类型为 DateTime。

我正在运行一个 for 循环来捕获所有日期(仅限日期,时间无关紧要,因此整个午夜)并根据日期提取哈希表中的每个值。代码:

$startdate = (get-date).AddDays(-30)
$today = get-date -format G
for($i = $startdate; $i -lt $today; $i=$i.AddDays(1))
{
   $z = $i -split " "
   $z = [datetime]$z[0]
   $z = Get-Date $z -format G
   "Comparing $z to: "
   $hash_dates.Keys | ? { $hash_dates[$_] -eq $z }
}

我使用了-format Gsplit 来确保格式匹配。但是循环永远找不到任何结果(即使它循环到 2016 年 11 月 1 日等)。我错过了什么吗?

【问题讨论】:

  • $today 是一个字符串。 $i -lt $today 没有意义
  • @MathiasR.Jessen 嗯。但是循环工作得很好。它从今天 30 开始并循环到今天,并且每次传递都输出 Comparing <DATE> to:。它只是没有找到任何哈希键。
  • @Zeno:$i -lt $today 按预期工作的唯一原因是 string $today 被重新转换为 [datetime] 用于比较,因为 LHS 的类型为 [datetime],但没有充分的理由将 $today 表示为字符串开头。

标签: powershell


【解决方案1】:

由于您的哈希表键是[datetime] 对象,因此根本不需要使用日期字符串和字符串解析: p>

$today = (Get-Date).Date # Note the .Date part, which omits the time portion
$startdate = $today.AddDays(-30)

# Note the change from -lt to -le to include today
for($i = $startdate; $i -le $today; $i = $i.AddDays(1))
{
  # Note that `echo` is an alias for `Write-Output`, which is the default,
  # so no need for an explicit output command.
  "Looking for $i..." 
  # Simply try to access the hashtable with $i as the key, which
  # either outputs nothing ($null), or outputs the value for that key.
  $hash_dates.$i
}

Re echo / Write-Output / 默认输出:请注意,您的状态消息将成为您的数据(输出)流,这可能是不受欢迎的。
考虑改用Write-Information


这里有一个简化的解决方案,展示了 PowerShell 的表现力:

$today = (get-date).Date

# Construct an array with all dates of interest.
$dates = -30..0 | % { $today.AddDays($_) } # % is a built-in alias for ForEach-Object

# Pass the entire array as the hashtable "subscript", which returns
# the values for all matching keys while ignoring keys that don't exist.
$hash_dates[$dates]

【讨论】:

    【解决方案2】:

    这是你想要的吗?

    $startdate = (get-date).AddDays(-30)
    $today = get-date -format G
    for($i = $startdate; $i -lt $today; $i=$i.AddDays(1))
    {
       $z = $i -split " "
       $z = [datetime]$z[0]
       Echo "Comparing $z to: "
       $z = Get-Date $z
       $hash_dates.$z
    
    }
    

    【讨论】:

    • 虽然通过键 ($hash_dates.$z) 访问哈希表以检索值是朝着正确方向迈出的一步,但您的答案并没有解决所有不必要且脆弱的日期到字符串的转换和解析。
    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 2014-06-01
    • 2012-04-21
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2021-07-09
    相关资源
    最近更新 更多