Powershell 循环哈希表中的日期?
我在Powershell中有一个如下所示的哈希表(Powershell 循环哈希表中的日期?,powershell,Powershell,我在Powershell中有一个如下所示的哈希表($hash_dates.GetEnumerator()| sort-Property name): 键的类型为DateTime 我正在运行一个for循环来捕获所有的日期(仅日期,时间不重要,因此都是午夜),并根据日期提取哈希表中的每个值。守则: $startdate = (get-date).AddDays(-30) $today = get-date -format G for($i = $startdate; $i -lt $today; $
$hash_dates.GetEnumerator()| sort-Property name
):
键的类型为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 G
和split
来确保格式匹配。但循环从未找到任何结果(即使它循环到2016年11月1日等)。我遗漏了什么吗?这就是你想要的吗
$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
}
由于您的哈希表键是
[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
}
Reecho
/Write Output
/默认输出:请注意,您的状态消息将成为数据(输出)流的一部分,这可能是不需要的。考虑使用,
下面是一个简化的解决方案,演示了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]
$today
是一个字符串<代码>$i-lt$today不允许sense@MathiasR.Jessen嗯,但是这个循环很好用。它从今天30开始循环到今天,并输出比较:
每次通过。它只是找不到任何散列键。@Zeno:$i-lt$today
按预期工作的唯一原因是字符串$today
被重新转换为[datetime]
进行比较,因为LHS的类型是[datetime]
,但是没有充分的理由将$today
表示为一个字符串作为开头。通过键($hash_dates.$z
)访问哈希表以检索值是朝着正确方向迈出的一步,您的答案并没有解决所有不必要且脆弱的日期到字符串的转换和解析。
$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]