The following script obtains a list of users under a specific OU in windows Active directory infrastructure. The users listed are enabled users and not disabled.
The environment trickles down like this:
Root Domain: Red929.com
Parent Organization Units – Users and Computers
Child Organization Units – Boston and New York > domain users/computers
What the script does – Uses “Get-ADOrganizationalUnit” cmdlet to retrieve the DistinguishedName and Name of the OU. Then from there, loop through all users with foreach loop to obtain only enabled users inside the OU, then list the results under array with Name, “Department” and “$OU.DistinguishedName” to make it readable. Finally, export the result to csv with export-csv cmdlet.
# Get the child OU by Site location
$Boston = Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Boston,OU=Users and Computers,DC=Red929,DC=com" -SearchScope OneLevel | Select-Object DistinguishedName
$NYC = Get-ADOrganizationalUnit -Filter * -SearchBase "OU=New York,OU=Users and Computers,DC=Red929,DC=com" -SearchScope OneLevel | Select-Object DistinguishedName,Name
# For each department in NYC
$Info = foreach ($OU in $NYC){
# get the users from each department by full name from NYC location. User must be enabled
$Users = Get-ADUser -Filter * -SearchBase "$($OU.DistinguishedName)" | Where-Object {($_.enabled -eq $true)}| Select-object Name,@{n='Department';e={$_.DistinguishedName -replace '^.*?,(?=[A-Z]{2}=)' -replace '^.*?,(?=[A-Z]{2}=)'}}
#List user and which OU/Department they belong to
$Users
}
$Info
#export result to csv
$Info | Export-Csv -Path "C:\temp\x.csv" -append -Force -NoTypeInformation
Results:

