Have Any Users Been Created In The Last Week?

This request came in a few days ago: “Can you make a script that will tell us what user accounts were created in the last X days?” the answer was, of course, “Sure!”

The script is pretty straightforward. This is the quick and dirty answer, so I don’t do any error catching or checks.

Param (
[Parameter(Position=0, Mandatory=$False)]

First, we want to get some information, namely how many days worth of account creations do we want to check. I use a default of 1 day.

Import-Module ActiveDirectory

I’ve been transitioning away from using the Quest AD PoSH tools to the MS ones. They both have their strengths.

$Today = Get-Date
$Date = $Today.adddays(-$Days)

The tricky bit here is knowing that the whenCreated field on an AD object (which we query for below) is a DateTime and therefore any comparisons we do with it should be of the same type. If I want all accounts created in the last 5 days, I just take the current time with get-date and subtract 5 days (or, more correctly, add –5 days).

$Users = Get-ADUser -filter { whenCreated -ge $Date } -properties whenCreated

Here is where we actually query AD. Using the filter, we check for accounts with a creation date greater than or equal to X days ago. We also want to include the whenCreated property in the objects returned so that we can display the creation time, should it be needed.

If ($Users) {
$Users | sort Surname | Select Name,DistinguishedName,WhenCreated
} Else {
Write-Host “No results found!” -ForeGroundColor Red

Finally, we return the results. For the purpose of this script, I just want to display the Name, DN and creation time, sorted by surname, on the screen. Therefore, I’ve piped the results to sort and select. I also write to the screen in red if no results are found. You could just as easily pipe the array to export-csv to save a report, or return the array and do further processing outside this script or function


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s