Search code examples
powershell

Compare between 2 different dates via powershell


I want to compare cutoffDate and LogonDate variables. I am using a function called Get-LastLogon. But it's not working properly.

PS C:\Windows\system32> $LogonDate
Monday, December 11, 2023 11:54:34 PM

PS C:\Windows\system32> $cutoffDate

Friday, June 7, 2024 10:33:45 AM

Script:

# Define the date 90 days ago from today
$cutoffDate = (Get-Date).AddDays(-90)

$LogonDate = (Get-LastLogon -Identity "user").DateTime

if ($LogonDate -lt $cutoffDate) {

#Do something
write-host "ok"

}

Solution

  • From the comments in the question, it appears that:

    $LogonDate  = [String]'Monday, December 11, 2023 11:54:34 PM'
    $cutoffDate = [DateTime]'Friday, June 7, 2024 10:33:45 AM'
    
    $LogonDate.GetType().Name
    String
    
    $cutoffDate.GetType().Name
    DateTime
    

    In PowerShell (as in most other loosely programming languages), the operand at the LHS (left hand side) of the operator, dictates the type casting used to align the operands types before executing the operation.

    This applies to most operators.

    '1' + 2
    12
    
    1 + '2'
    3
    

    Which means that if the string type ($LogonDate) is at the LHS, you will do a string compare:

    $LogonDate -lt $cutoffDate
    False
    

    Note here that even Monday, December 11, 2023 11:54:34 PM comes before Friday, June 7, 2024 10:33:45 AM, the comparison is False because the M in Monday isn't less than the F in Fryday.

    In other words, the solution to your issue is to swap the operands and negate the operator (the opposite of the -lt operator is: -ge) so that the DateTime type ($cutoffDate) is at the LHS and consequently a DateTime compare is preformed:

    $cutoffDate -ge $LogoDate
    True
    

    For more details, see the (as of today) updated about comparison operators document.