PowerShell; Search all Domain Controller Event Logs for Keywords

Do you need to know the last time a user logged on, or who created an AD account? As long as you have audit logging enabled, the data you are after is in the event logs of your domain controllers. The problem is, if you have more than one domain controller (you should) the record that you need can be on any of them.

At my day job, we have quite a few DCs and I needed to know which admin created a particular AD account. There was no way I was going to logon to dozens of servers and search them one at a time. PowerShell to the rescue!

Import-Module ActiveDirectory

$keyword = Read-Host "Enter Keyword"
$eventid = Read-Host "Enter EventID"
$logname = Read-Host "Enter the name of log you want to search, application, security, etc."

$domains = (Get-ADForest).domains
$dcs = Foreach ($domain in $domains) {
     Get-ADDomainController -Filter *|Select Name -ExpandProperty Name|sort-
     object|get-unique
}
$events = ForEach ($dc in $dcs) {
     Get-EventLog  -ComputerName $dc -LogName $logname -InstanceId $eventid -
     Message *$keyword*|Select-Object -Property *
}
$events|out-file $env:usersprofile\documents\dc_log_search.txt

This short ‘n sweet bit of code will scan your domain and find all the domain controllers. Occasionally DCs run more than one role and show up multiple times in the output of this cmdlet so we drop the duplicate names.

Then it will prompt you for a keyword to search for. In the case of account data you’d enter the samaccount name. You could also enter the name of a workstation or server for example. Next it will ask you for an Event ID Number. Finally it will ask for the name of the log; application, security, system, etc. to search.

The script will loop through each DC and find the events you’ve described. Each matching record will be output to a text file named dc_log_search.txt in your documents folder. It wouldn’t take much effort to turn this data into an HTML report, email notification, or even an archival tool.

About Kevin Trent

IT professional with almost 30 years of experience in Infrastructure, Architecting, Administration, Development, and Communications.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s