Systemspoet
Systemspoet

Reputation: 142

Get-ADUser Filter AccountExpirationDate

I'm observing a discrepancy between how Active Directory date objects are set vs how they are retrieved and searched with -Filter. Observe:

First I set an expiration date:

PS C:\WINDOWS\system32> set-aduser testaccount -AccountExpirationDate '12/25/2024 00:05:00' -Credential $CRED 

PS C:\WINDOWS\system32> Get-ADUser testaccount -Properties AccountExpirationDate 


AccountExpirationDate : 12/25/2024 12:05:00 AM
DistinguishedName     : CN=Test Account,OU=Test,OU=CU Users,DC=ad,DC=contosso,DC=com
Enabled               : True
GivenName             : Systems
Name                  : Test Account
ObjectClass           : user
ObjectGUID            : {snip}
SamAccountName        : testaccount
SID                   : {snip}
Surname               : Test1c
UserPrincipalName     : [email protected]

Then I try to search for all users with that Expiration Date, a couple of ways:

PS C:\WINDOWS\system32> Get-ADUser -Filter 'AccountExpirationDate -eq "12/25/2024 00:05:00"' -Credential $CRED

PS C:\WINDOWS\system32> 
PS C:\WINDOWS\system32> Get-ADUser -Filter 'AccountExpirationDate -eq "12/25/2024 12:05:00 AM"' -Credential $CRED

PS C:\WINDOWS\system32> 

PS C:\WINDOWS\system32> $T=(get-date '12/25/2024 12:05:00 AM')

PS C:\WINDOWS\system32> Get-ADUser -Filter 'AccountExpirationDate -eq $T' -Credential $CRED

PS C:\WINDOWS\system32> 

Nada. I figure I'm missing something between how AD stores that date value and how it's retrieved and displayed.

Upvotes: 2

Views: 2460

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 61303

AccountExpirationDate is a friendly attribute given by the AD Module and it represents the translation from file time of AccountExpires. Looking at your snippets, one of them should work properly:

Get-ADUser -Filter 'AccountExpirationDate -eq $T'

The above is only failing because the date you're seeing in AccountExpirationDate has been converted to your local time, if you want to query back for a user having that exact date set you would need to convert that date ToUniversalTime() beforehand:

$T = (Get-Date '12/25/2024 12:05:00 AM').ToUniversalTime()
Get-ADUser -Filter 'AccountExpirationDate -eq $T' -Credential $CRED

In this case, while using a literal string ', the datetime instance ($T) is passed as-is to the AD Filter provider which then converts this date .ToFileTime().

The other examples will never work because the AD Filter is receiving a date in the format of MM/dd/yyyy HH:mm:ss and it has no clue how to deal with that.

If you wanted to use a expandable string " for your filter you would need to do the following:

$date = (Get-Date '12/25/2024 12:05:00 AM').ToUniversalTime().ToFileTime()
# this:
Get-ADUser -Filter "accountExpires -eq '$date'"
# or this:
Get-ADUser -Filter "accountExpirationDate -eq '$date'"

Upvotes: 1

Related Questions