gpt4 book ai didi

powershell - 遍历哈希表中的日期?

转载 作者:行者123 更新时间:2023-12-03 01:10:12 24 4
gpt4 key购买 nike

我在 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

key 的类型为 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 日等)。我错过了什么吗?

最佳答案

由于您的哈希表键是 [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]

关于powershell - 遍历哈希表中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40514236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com