I would like to query all AD users and get the following attributes from each user:
SamAccountName, UserPrincipalName, LastLogonDate, Enabled, LockedOut, PasswordNeverExpires, CannotChangePassword, whenCreated
As the domain has more than one domain controller I also want to make sure I get all the data. Any thoughts?
Many thanks
Here my code:
$domainControllers = Get-ADDomainController -Filter * | Select-Object -ExpandProperty Name
Write-Host "Create AD user report accross the following domaincontroller: $domaincontrollers"
# Create an empty array to store the results
$results = @()
$searchbase= "DC=XXX,DC=XX"
# Iterate through each domain controller and retrieve users
foreach ($dc in $domainControllers) {
$users = Get-ADUser -Filter * -SearchBase $Searchbase -Properties SamAccountName, UserPrincipalName, LastLogonDate, Enabled, LockedOut, PasswordNeverExpires, CannotChangePassword, whenCreated |
Select-Object SamAccountName, UserPrincipalName, @{Name="LastLogin"; Expression={$_.LastLogonDate}}, Enabled, LockedOut, PasswordNeverExpires, CannotChangePassword , whenCreated
$results += $users
# Export the results to a CSV file
}
$resultfinal = $results | Select-Object * -Unique
$resultfinal| Export-Csv -Path c:\logging\data\AD_User_Report.csv -NoTypeInformation
However often I simply get nothing back and I'm not sure why exactly. Probably it's related the "unique" sorting option?
Based on the domain spot checks (attribut editor) every user object would have the lastlogonDate so the domain schema should be up-to-date.