Ever felt the need to query all the users from active directory? Below is a script that will query all the users in an active directory forest. First it will fetch all the domains in a forest. It will then pick each domain and query all the users of that domain.
It will export samaccountname, emailaddress, enabled status and the domain name of each user in a csv file. This script will can be also be used if you want to get the user enabled / disabled status. You can add, remove any other properties of the user object by editing the script.
You need to make sure that the system from where you are running the script should have port 389 opened to the domain controllers of each domain. Mostly it will select the domain controller of the same AD site or the nearest AD site. Just remember to have RSAT tool installed if you are not running the script on the domain controller.
$Domains = (Get-ADForest).domains
foreach ($Domain in $Domains)
{
Get-ADUser -Server $Domain -Filter * -Properties samaccountname, emailaddress, enabled, canonicalname -ResultPageSize 5000 | select samaccountname, emailaddress, enabled, @{Label="Domain";expression={(($_.canonicalname) -split "/")[0]}} | Export-Csv D:\all_users.csv -Append -NoTypeInformation
}
The above script will export the user's select properties to a csv file.
Comments