Forum Discussion

MrMartinITPro's avatar
MrMartinITPro
Copper Contributor
Sep 15, 2023

Date comparison does not work

I am attempting to write a file detection script, but PowerShell doesn't seem to recognize that the file dates are equal. Here's what I'm experiencing:

 

PS C:\> $FileDate = Get-Date -Date "2023-05-08T11:00:31"
PS C:\> $FileDate

Monday, May 8, 2023 11:00:31 AM

PS C:\> $FileDate.GetType()

IsPublic IsSerial Name                                     BaseType        
-------- -------- ----                                     --------        
True     True     DateTime                                 System.ValueType

PS C:\> $TestDate = (Get-Item 'C:\Windows\System32\drivers\etc\hosts').LastWriteTime
PS C:\> $TestDate

Monday, May 8, 2023 11:00:31 AM

PS C:\> $TestDate.GetType()

IsPublic IsSerial Name                                     BaseType        
-------- -------- ----                                     --------        
True     True     DateTime                                 System.ValueType

PS C:\> if ($FileDate -eq $TestDate) {$true} else {$false}
False

 

 

 

1 Reply

  • MrMartinITPro's avatar
    MrMartinITPro
    Copper Contributor

    Found the problem. Here's the fix:

     

    $TestDate = (Get-Date -Date '2023-05-08T11:00:31').DateTime
    $FileDate = ((Get-Item '%redacted%').LastWriteTime).DateTime
    
    if ($FileDate -eq $TestDate) {
        Write-Host "Detected"
        Exit 0
    }
    
    else {
        Write-Host "Not detected"
        Exit 1
    }

Resources