Reputation: 339
My data($messages) looks like this
Source: sourceA
Message : {@{messagetext = abc;publishedtime = 10/5/2020}, @{messagetext = def;publishedtime = 10/12/2020}
I am trying to filter the message by displaying only messages that happened from last week until now then combining it with the source property. It is possible that a source may have multiple lines if several publishedtime happened last week.
$filterDate = (Get-Date).AddDays(-7)
$messages | select source, @{n='messagetext' ; e={???}} , @{n='publishedtime' ; e={???}}
I am lost on how to add the calculated property with the condition. I was also thinking if this could be done with a loop.
I also tried the following but having some errors
$Messages | Where-Object {([DateTime]($_.messages).publishedtime).ToUniversalTime() -ge $filterDate} but having some error
Upvotes: 0
Views: 49
Reputation: 61103
I think you should always compare dates to dates, and not compare a datetime object to a string, especially since in your question it is unclear what exact format the date is in.
Probably the format used is 'M/d/yyyy'
, but it could just aswell be 'd/M/yyyy'
or even '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}
Upvotes: 1
Reputation: 24071
There is no need to use a calculated property. First filter the $messages
collection by date. Like so,
$filterDate = (Get-Date).AddDays(-7)
$lastWeek = $messages | ? { $_.PublishedTime -ge $filterDate }
Now the $lastWeek
collection contains only messages that were published within a week. Depending on the exact format of PublishedTime
and your locale settings, it might need to be parsed as a date. If that's the case, please edit the question and show a few examples of actual data. Sanitize the messages if needed.
Upvotes: 1