DateTime -lt issue

Using DateTime to output the date a user was added to a AD group is then output to csv using Add-Member -type Noteproperty -Name DateAdded -Value $today. Whatever date shows in the csv, the return value is always true (i.e. less than) so is always removed from the group using Remove-ADGroupMember.

I manually change a csv line DateAdded value to say for example a month ago, and that user is removed from the group. However, it also removes any other lines in the csv that have todays date or any date that should not be less than $fortnight.

This is part of the script

$today = ([DateTime]::Today).ToFiletime()
$fortnight = ([DateTime]::Today.AddDays(-14)).ToFiletime()

        ##Loop through AD group to remove any are older than 14 days
        foreach ($ADObject in $members) {
        $lineitem = $filegroup | Where-Object {$_.SamAccountName -like $ADObject.SamAccountName}
        if (($lineitem -ne $null) -and ($lineitem.DateAdded -lt $fortnight)) {
                Remove-ADGroupMember -Identity $group -Members $Lineitem.SamAccountName -Confirm:$false -WhatIf
                $filegroup = $filegroup | Where-Object {$_.SamAccountName -ne $ADObject.SamAccountName}
                $acctsDeleted++
            }
        }

Thanks
David

I have had issues using -lt -gt with datetime objects as well. What solved it for me was to hard cast it even though I knew I had a datetime object and that worked for me.

if (($lineitem -ne $null) -and ([DateTime]$lineitem.DateAdded -lt [DateTime]$fortnight))

Thanks for the reply. Doesnt like it though

I get combination of
Cannot convert value “1.30775E+17” to type “System.DateTime”. Error: “The string was not recognized as a valid DateTime. There is an unknown word starting at index 7.”
and
Cannot convert value “130805244000000000” to type “System.DateTime”. Error: “String was not recognized as a valid DateTime.”

These errors go away if i use ToUniversalTime, but the original issue is still there showing everything as less than.

Why are you converting them to a file time? If the date values are coming from a CSV, they are not dates, everything is a string and must be re-converted to date\time. By converting them to a file time, you are converting them to a string. You are getting errors because you are converting a datetime into string (i.e. .ToFileTime()) and then trying to recast the string into a datetime. First, eliminate the .ToFileTime(). Make sure that the value that is coming from the CSV is converted to a datetime and then compare that to the manual date you generating with the -14. Then you are comparing dates and not strings.

It’s a little hard to get all of the logic you are attempting with doing an AD pull, a CSV pull and a how the dates all correlate.

I see. Managed to sort it with a function I found to change back to system.datetime

Cheers