Find Hostnames per UserID in Event Logs on Domain Controllers

$targetAccounts=Get-Content "C:\Users\kimconnect\Desktop\targetAccounts.txt"

function Get-UserComputerName {
Searches a specified Domain Controller for the computername of a logged on user.
Queries a DC for Event ID 4768 (Kerberos authentication ticket,TGT) request from the servers Security
event log.
SamAccount name of the user to search for
PS> .\Get-UserComputerName -UserName "John_Doe" -Server "My_DC"
Searches for user John_Doe on Domain Controller My_DC
PS> .\Get-UserComputerName -Username "John_Doe"
Searches for user John_Doe using the logged on server name for the current user
running the script.
PS> .\Get-UserComputerName
Searches the current user on the logged on server name
param([string]$username = $env:username,[string]$server = $env:logonserver)
$ErrorActionPreference = "silentlycontinue"
if ($server.StartsWith("\\dc")) {$server = $server.Remove(0,2)}
$events = Get-WinEvent -ComputerName $server -MaxEvents 5 -FilterHashTable @{logname="security";id=4768;data=$username}
# Check if error has been raised from EventLog Query.
if (!$?) {
Write-Warning "No successful logon events were found on Server: $server for Username: $username"
foreach ($event in $events) {
$myObject = New-Object -TypeName system.Object
[string]$Computer = $event.message.split("`n") | Select-String "Client Address"
$addressLine = $computer.replace("Client Address:",'')
$addressLine = $addressLine.trim()
if ($addressLine.startswith("::ffff:")) { $address = $addressLine.replace("::ffff:",'') }
$DNSResult = [system.Net.Dns]::Resolve($address)
$ComputerName = $DNSResult.HostName
$timeStamp = $event.timecreated
$myObject | Add-Member -MemberType noteproperty -Name AuthDC -Value $server
$myObject | Add-Member -MemberType noteproperty -Name TimeStamp -Value $timeStamp
$myObject | Add-Member -MemberType noteproperty -Name UserName -Value $username
$myObject | Add-Member -MemberType noteproperty -Name IPAddress -Value $address
$myObject | Add-Member -MemberType noteproperty -Name ComputerName -Value $computerName

function listControllers{
$domain = [directoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name

# Optimized method
$dcList=(nltest /dclist:$domain)
$dcList = $dcList[1..($dcList.Length-2)] -replace "*.*" -replace ".* "

<# Unoptimized
$dcs = ($domain.FindAllDomainControllers() | findstr /B /C:"Name") -replace ".* : "

$targetAccounts | Foreach-Object -Process{
listControllers | Foreach-Object{
Get-UserComputerName -UserName "$username" -Server "$_"

Leave a Reply

Your email address will not be published. Required fields are marked *