Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views1 page

Last Loggedon User Script

This PowerShell script connects to all Active Directory computers with 'Server' in their OS name to retrieve the last logged on user from the registry. It handles connection errors gracefully and stores the results in a list, which can be displayed in a table format or exported to a CSV file. The final report is saved to 'C:\Temp\LastLoggedOnUsers.csv'.

Uploaded by

vslrinfotech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Last Loggedon User Script

This PowerShell script connects to all Active Directory computers with 'Server' in their OS name to retrieve the last logged on user from the registry. It handles connection errors gracefully and stores the results in a list, which can be displayed in a table format or exported to a CSV file. The final report is saved to 'C:\Temp\LastLoggedOnUsers.csv'.

Uploaded by

vslrinfotech
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

# 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

You might also like