PowerShell queries user accounts under each OU
# define top-level OU
$OUs = Get-ADOrganizationalUnit-SearchBase "OU=XXX,DC=Contoso,DC=com"-Filter *
# define an array for storing data
$UserList = @ ()
# traversing OU
Foreach ($OU in $OUs)
{
# query all users of the current OU
$Users = Get-ADUser-SearchBase $OU-Filter *-SearchScope 1
# traversing users
Foreach ($User in $Users)
{
# add user name and OU information to the array
$UserList + = [PSCustomObject] @ {
OU = $OU.Name
Name = $User.Name
}
}
}
# output information
$UserList