Back in May of 2022, I was dealing with an onslaught of security incidents. Each of these incidents seemed to target Active Directory in one way or another. During one of the incidents I dealt with earlier in the month, I wrote some scripts to help me throughout my investigation phase. A few of these scripts I wrote have some broader applications beyond security, so I figured I’d share one of them with you in case you are looking to determine when accounts were created in the Active Directory you find yourself workin in.
How to Find What Active Directory Users Were That Were Created In The Last [Number Of] Days
Managing an Active Directory that sees a lot of user turnover in short periods creates a need for better oversight. This script helps to figure out who was created in the last so many days. In my case, I needed to see user additions to a particular Active Directory over the previous 180 days.
This PowerShell script works on 4.0 but will also work on PowerShell 5.1.
Step 1: Copy this script and save it as get_users_created_in_(number here)_days.ps1
Make sure to change (number here) to the number of days that you want to look back from. Change the numbers on lines 8 and 9. In this example I have 30 days set as my time horizon.
PowerShell Script:
# This script will get users created in the last 180 days, and dump the results to text
# in the SAME DIRECTORY that you are running the script from.
# To change time, edit the (180) in .AddDays(-180).Date line.
# -Rick
$prvDate = ((Get-Date).AddDays(-30)).Date
Get-ADUser -Filter {whenCreated -ge $prvDate} -Properties whenCreated | Select Name, whenCreated | Sort-Object whenCreated | Out-File -FilePath .\users-last-30.txt
Step 2: Run this script in Powershell on a server or VM with the Get-ADUser cmdlet.
To do this, open up Powershell as an administrator, and run the command as follows:
PS C:\> get_users_created_in_(number here)_days.ps1
Step 3: Open the output file
The script will dump the list into a text file you can review visually. It will save in the same directory as the script.
Closing Thoughts
To get anything useful out of Active Directory, you should have a cursory understanding of PowerShell. But, unfortunately, I run into admins throughout the community who don’t know any PowerShell commands (or any scripting language, for that matter). The distribution between junior and senior admins who don’t grasp scripting is almost 1:1; I’ve come to find. So, if you are one of those administrators, you should start a repository of scripts and make this the first one you commit to that repo.