# Define the OU path where your servers are located
$ouPath = "OU=servers,DC=domain,DC=local" # Replace with your OU path
# Get a list of servers in the specified OU
$servers = Get-ADComputer -Filter {OperatingSystem -like "Windows Server*"} -SearchBase $ouPath | Select-Object -ExpandProperty Name
# Loop through each server and query logged-on users
foreach ($server in $servers) {
try {
# Use WMI to query logged-on user information
$loggedOnUsers = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $server | Select-Object -ExpandProperty UserName
if ($loggedOnUsers) {
Write-Host "Logged-on users on $server"
$loggedOnUsers | ForEach-Object {
Write-Host " $_"
}
} else {
Write-Host "No users logged on to $server"
}
} catch {
Write-Host "Failed to query $server"
}
}
If you want to search by specific names, you can adjust the filter to this –
Get-ADComputer -Filter {Name -like "AZ-EUW-*"} -SearchBase $ouPath