# Load AD module
Import-Module ActiveDirectory
# List to hold results
$results = @()
# Get all AD computers with 'Server' in the OS name
$servers = Get-ADComputer -Filter {OperatingSystem -like "*Server*"} -Property
Name, DNSHostName
foreach ($server in $servers) {
$hostname = $server.DNSHostName
if ($hostname) {
Write-Host "Connecting to $hostname..." -ForegroundColor Cyan
try {
# Try to read last logged on user from registry
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',
$hostname)
$key = $reg.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\
Authentication\\LogonUI")
$lastUser = $key.GetValue("LastLoggedOnUser")
# Add to result list
$results += [PSCustomObject]@{
ServerName = $server.Name
DNSHostName = $hostname
LastLoggedOnUser = $lastUser
}
}
catch {
Write-Warning "Could not connect to $hostname or retrieve user info.
Error: $_"
$results += [PSCustomObject]@{
ServerName = $server.Name
DNSHostName = $hostname
LastLoggedOnUser = "Unavailable"
}
}
}
}
# Display results
$results | Format-Table -AutoSize
# Optional: Export to CSV
$results | Export-Csv -Path "C:\Temp\LastLoggedOnUsers.csv" -NoTypeInformation -
Encoding UTF8
Write-Host "`nReport saved to C:\Temp\LastLoggedOnUsers.csv" -ForegroundColor Green