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

标签 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

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/

相关文章:

powershell - 无法让 powershell 脚本在 PowerGUI 中运行

powershell - 在Powershell中作为副作用输出

powershell - 从 PowerShell 调用 Get-AuthenticodeSignature 的结果不一致,通常说 NotSigned

powershell - Powershell-NewItemUnauthorizedAccessError

相当于 "tail"命令的 Powershell 几乎可以远程工作

c# - 将自定义对象从 C# 传递到 Powershell

powershell - 在 Powershell 中调用 Exchange 命令 - 数据部分中不允许出现 block

azure - 组合和匹配 Get-AzureADUser、Get-AzureADSubscribedSku 、 Get-AzureADUserManager 的输出

windows - 使用 Powershell [DateTime]::ParseExact - 有趣的字符串?

java - 通过 Java 查询 Active Directory