Reputation: 11
I have a CSV file with several rows and a date column. I want to grab all rows that have a date is more than 30 days old. Here is my best attempt:
$Data = Import-CSV "H:\Data.csv"
$CutoffDate = (Get-Data).AddDays(-30)
$Data | Where-Object {$_.Date -lt $CutoffDate}
This does not return anything and there are definately rows with dates older than 30 days. My guess is that $_.Date
is not recognized as a date, but that being the case I'm stumped on how to make it do so. Can anybody point me in the right direction here? Thanks. -Al
Upvotes: 0
Views: 5053
Reputation: 54881
When you import data using Import-CSV
, all properties are created as strings. To filter by date, you need to make the date a datetime
object. The sample had a typo on the second line ( Get-Data
instead of Get-Date
) too. Try this:
$Data = Import-CSV "H:\Data.csv"
$CutoffDate = (Get-Date).AddDays(-30)
$Data | Where-Object {$_.Date -as [datetime] -lt $CutoffDate}
You could combine it with Import-CSV
if you want, like this:
$CutoffDate = (Get-Date).AddDays(-30)
$Data = Import-CSV "H:\Data.csv" | Where-Object {$_.Date -as [datetime] -lt $CutoffDate}
Upvotes: 3