Search code examples
powershellcsvdatedate-comparison

PowerShell Date Comparison


Goal: Import dates from CSV. If date has already passed or is today, display it.

$dayInOctober = (Get-date).AddDays(90)
$csvname = "myCSV.csv"
$csvFile = Import-Csv C:\Users\a341162\Desktop\$csvname

foreach($row in $csvFile){
    if ($row.Date -le $dayInOctober){
        Write-Host $row.Date
    }
}

But only works if I make the if statement -gt. Shouldn't it be the way I have it above?

myCSV.csv:

"Name","Date"
"admryantest2","7/20/2018"
"admryantest3","7/20/2018"
"admryantest3","7/23/2018"
"admryantest3","7/23/2018"

Solution

  • When you import the CSV, $row.Date is a string. If you want to compare dates as dates then you need to convert it to a date:

    $dayInOctober = (Get-date).AddDays(90)
    $csvname = "myCSV.csv"
    $csvFile = Import-Csv C:\Users\a341162\Desktop\$csvname
    
    foreach($row in $csvFile){
        if ((Get-Date $row.Date) -le $dayInOctober){
            Write-Host $row.Date
        }
    }
    

    Then you can use -le as expected.