Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering dates using PowerShell

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:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

enter image description here

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading