Querying date based Active Directory fields
Another “from usenet to blog” entry. Someone wanted to a list of all users in their Active Directory created after a specific day. Like most AD related tasks, this is fairly easy in Powershell, but you do have to be aware of one tricky piece. LDAP queries require a specially formatted string to represent date/time. For this, we’ll query the ‘whenCreated’ field of the AD. Here’s an example that returns all users from AD that were created in the last 15 days:
$past = [datetime]::UtcNow.adddays(-15)
$ldappast = "{0:0000}{1:00}{2:00}000000.0Z" -f $past.year,$past.month,$past.day
$s = new-object directoryservices.directorysearcher([ADSI]'')
$s.filter = "(&(objectcategory=person)(objectclass=user)(whenCreated>=$ldappast))"
$s.findall()
$ldappast holds the date in the specific format needed when comparing date/times in LDAP: YYYYMMDDHHMMSS.TZ. An example of March 12, 2007 00:00 represented in this format would be: 20070312000000.0Z. By the way, “0Z” indicates UTC.
gaurhoth