首页 > 解决方案 > 在powershell中将对象和数组与条件结合起来

问题描述

我的数据($messages)看起来像这样

Source: sourceA
Message : {@{messagetext = abc;publishedtime = 10/5/2020}, @{messagetext = def;publishedtime = 10/12/2020}

我试图通过仅显示从上周到现在发生的消息然后将其与源属性结合来过滤消息。如果上周发生了多个发布时间,则一个来源可能有多行。

$filterDate = (Get-Date).AddDays(-7)    
$messages | select source, @{n='messagetext' ; e={???}} , @{n='publishedtime' ; e={???}} 

我不知道如何将计算出的属性与条件相加。我也在想这是否可以通过循环来完成。

我也尝试了以下但有一些错误

$Messages | Where-Object {([DateTime]($_.messages).publishedtime).ToUniversalTime() -ge $filterDate} but having some error

标签: powershell

解决方案


我认为您应该始终将日期与日期进行比较,而不是将日期时间对象与字符串进行比较,尤其是因为在您的问题中不清楚日期的确切格式。
可能使用的格式是'M/d/yyyy',但它也可以是'd/M/yyyy'甚至是'MM/d/yyyy'

$dateFormat = 'M/d/yyyy'  # <-- this is unclear in the question, could also be 'd/M/yyyy' or 'MM/d/yyyy'

# you can set the Time part to all zero, as the dates in the $Messages objects also do not have that
$filterDate = (Get-Date).AddDays(-7).Date  
$Messages | Where-Object {[DateTime]::ParseExact($_.Message.publishedtime, $dateFormat, $null) -ge $filterDate}

推荐阅读