powershelldatetime-formatdate-arithmeticget-aduser

Powershell Query does not calculate correct Date


HelloThere,

we get AD-Users from an import script that runs daily and if a user was found in a csv we write the current date in the extensionattribute1 in format "dd-MM-yyyy". Now we want to calculate if a AD user has a different date in the extensionattribute1 (minus 90 days) then we want to inform their managers what should happen to those accounts.

Interesting is, with my query we get correct Users and some Users between 30 and 90 Days. I don't know what is wrong in my code or with the syntax - can someone pls help? Thanks

sorry, i am not a PowerShell Pro by now but working on it :D Greetings


# get date -90 Days
$date = (Get-Date).AddDays(-90).ToString("dd-MM-yyyy")
$date
# it gets "27-08-2022" -> so the script should only show users less than this date


# query for extensionattribute1 less than 90 days 
get-aduser -properties ExtensionAttribute1 -filter {(enabled -eq "true") -and (extensionAttribute1 -gt $date)}


# here the output is partial correct, we get users with an extensionattribute1 from 
# 31-05-2022
# 30-06-2022
# 29-07-2022
# but also some Users with a date from between 30 and 90 days what is incorrect =/
# 30-09-2022 
# 31-10-2022 

Solution

  • You should not compare date strings against eachother, especially not when you use date format "dd-MM-yyyy", since that is a non-sortable date format. (you might get away with it if you would have used format 'yyyy-MM-dd'..)

    Instead, convert the value found in the ExtensionAttribute1 to a DateTime object first and compare that to a real reference DateTime object.

    Try

    # get date -90 Days
    $date = (Get-Date).AddDays(-90).Date  # set to midnight with time part '00:00:00'
    
    # query for extensionattribute1 less than 90 days 
    Get-ADUser -Properties ExtensionAttribute1 -Filter 'Enabled -eq $true -and ExtensionAttribute1 -like "*"' | 
    Where-Object {[datetime]::ParseExact($_.ExtensionAttribute1, 'dd-MM-yyyy', $null) -gt $date}