在哈希表中循环日期?

时间:2016-11-09 19:07:23

标签: powershell

我在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日等)。我错过了什么吗?

2 个答案:

答案 0 :(得分:3)

由于哈希表键是[datetime]个对象根本不需要使用日期字符串 和字符串解析:

$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
}

重新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]

答案 1 :(得分:0)

这是你想要的吗?

$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

}