Get Active Directory Accounts Created in the Last N Days (featuring -xor)

A customer asked me to demonstrate how you can check for user or computer accounts recently added to a domain.

The result was this function:

Get-ADNewlyCreatedAccount

 

The function has the following parameters and switches:

  • $Domain... the target domain
  • $WithinDays... the number of days history to include in the search
  • $UsersOnly... get only newly created user accounts
  • $ComputersOnly... get only newly created computer accounts

 

It allows you to specify a point in time after which you want details of any accounts added to the domain. By default it will output both user accounts and computer accounts. However, you can ask for just one these account types to be returned in your results.

Now, there's something in this function that you don't see too often - the use of the -xor logical operator.

$UsersOnly -xor $ComputersOnly

What does it do? Well, it says only return true when one of the conditions is evaluated as true and the other one as false. Let's take a closer look...

As we've seen, the function has two switches: one is -UsersOnly, the other is -ComputersOnly. They do exactly what you'd expect. How? We need to handle the following scenarios:

  1. neither switch supplied
  2. just -UsersOnly switch supplied
  3. just -ComputersOnly switch supplied
  4. BOTH of the switches supplied

 

And, that's where -xor comes into its own...

If ($UsersOnly -xor $ComputersOnly) {...}

Else {

$LDAPFilter = "(&(objectclass=user)(whenCreated>=$CutOffDate))"

}

If we DON'T have a condition where ($UsersOnly is true and $ComputersOnly is false), or a condition where ($UsersOnly is false and $ComputersOnly is true), then we execute the code in the Else script block (this handles scenarios 1 and 4). This code defines an LDAP filter that collects all user and computer accounts (yes, I know it says objectclass=user!) that have a whenCreated value greater than or equal to the $CutOffDate variable ($CutOffDate is constructed earlier in the function from the value supplied to the  -WithinDays parameter).

What if the -xor statement returns true?

If ($UsersOnly -xor $ComputersOnly) {

If ($UsersOnly) {

$LDAPFilter = "(&(ObjectCategory=Person)(ObjectClass=User)(whenCreated>=$CutOffDate))"

}

Else {

$LDAPFilter = "(&(ObjectClass=Computer)(whenCreated>=$CutOffDate))"

}

}

 

Here, we know either one of $UsersOnly or $ComputersOnly will be true, so we can then test which one actually is true. Depending on the result, we define an LDAP filter to either search on just Users or just Computers. This satisfies scenarios 2 and 3.

Now we can perform the search with the defined LDAP filter...

Get-ADObject -LDAPFilter $LDAPFilter -Properties WhenCreated -Server $DomainFqdn

Using the function...

XOR gives you more!