I realize this should be a simple task, but I am not seeing the results that I expect to see. I am importing a CSV file and trying to filter out the dates that have already passed and only keep the dates that are equal to today or in the future.
As a simple example, I have a csv file with the following:
If I run the following code, I am not seeing the expected results; dates that are equal today or in the future:
$Today = Get-date
$data = import-csv C:\temp\ReleaseRequest2.csv
$data | where {$_.expires -ge $Today} | select expires
When I run the above, I receive the following results:
The goal is to only return dates that are equal to today or in the future. Is there formatting of the dates that I need to do before trying to filter them? I know it is a simple solution, but I am banging my head against a wall trying to figure it out.
Thank in advance.
Convert the dates into a datetime
object before you compare them, you can see why your code is failing with this simple test:
$today = Get-Date
'11/26/2024 8:55' -ge $today # true
[datetime] '11/26/2024 8:55' -ge $today # false
So, in your filtering condition if you add the cast to [datetime]
the issue should be solved:
$today = Get-Date
$data = Import-Csv C:\temp\ReleaseRequest2.csv
$data | Where-Object { [datetime] $_.Expires -ge $Today }
Using Get-Date
to parse them should also work:
$data | Where-Object { (Get-Date $_.Expires) -ge $Today }
If those options above fail to convert the strings into datetime
objects, you can use datetime.ParseExact
with the format strings your dates have, for example:
[datetime]::ParseExact(
'1/28/2025 8:55', 'M/d/yyyy H:mm', [cultureinfo]::InvariantCulture)