How to Filter CSV Dates in DD/MM/YYYY Format Using PowerShell?

0
11
Asked By QuirkyQuokka27 On

I'm working with a CSV file that has a column named 'lastseen' containing dates in the format DD/MM/YY HH:MM:SS. I need to filter these records to find dates that are older than 80 days from today. Here's what I've tried:

```powershell
$CurrentData = Import-Csv $CsvPath
$80Day = (Get-Date).AddDays(-80)
($CurrentData | Where-Object {$_.LastSeen -gt $80Day})
```

However, I'm getting unexpected results. There are only 208 records total, all with a value in the 'lastseen' column. The closest date is 30 days ago and the farthest is 100 days ago. But when I test with `$80Day = (Get-Date).AddDays(-30000)`, I get 156 results, and with `$80Day = (Get-Date).AddDays(-10)`, I get 138 results. Do I need to convert the date format before comparing it?

5 Answers

Answered By MysterySolver On

There is a built-in cmdlet like `Get-FormatDate` that can help format dates correctly. If you search a bit, you'll find it useful to handle date formats without too much hassle.

Answered By CleverCoder On

Check the comparison type on the left side; it might need adjustment. Try this:

```powershell
$CurrentData | Where-Object {$_.LastSeen -le $80Day}
```
This ensures you're properly comparing against your cutoff date.

Answered By TechieTommy On

You might want to start by converting the date in your 'lastseen' field to the ISO8601 format, or better yet, fix the CSV file if possible to avoid this issue altogether.

Answered By CodingNinja99 On

Use `[System.DateTime]::ParseExact` to convert the 'LastSeen' field to a `DateTime` format that can be compared against the date from `Get-Date`. Try this:

```powershell
($CurrentData | Where-Object {[System.DateTime]::ParseExact($_.LastSeen,'dd/MM/yyyy HH:mm:ss',[System.Globalization.CultureInfo]::InvariantCulture) -gt $80Day})
```
This way, you ensure you're comparing `DateTime` types. Just a friendly tip: remember that `HH` is for 24-hour format while `hh` is for 12-hour format!

Answered By PowerfulPenguin On

You could also try casting the 'lastseen' date to a datetime format, but remember, use `[datetime]`, not `[date]`. Just be careful, as the string format should match the expected format for conversion, or you'll get errors!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.