How to create a table with a list of OU in AD using powershell

Viewed 159

I have in my active directory a number of subfolders and I want to count the number of users there. I found a way to do with powershell and the Get ADUser command, however I think there must be a way to optimize this to build a table with all the subfolders I want.

enter image description here

normally the following script works for me, but I don't know if I can recursively go through all the subfolders and finally create a csv with the number of users per subfolder.

echo "ACC - total:" (Get-ADUser -Filter * -SearchBase 'OU=Users,OU=ACC,OU=Clients,DC=SSICloud,DC=local' ).count

 echo "All Car - total:" (Get-ADUser -Filter * -SearchBase 'OU=Users,OU=All Car,OU=Clients,DC=SSICloud,DC=local' ).count

outcome:

ACC - Total:
10

All Car - Total: 
11

Thank you

1 Answers

Get-ADOrganizationalUnit can search recursively through all OUs in your Domain, you can then pass the DistinguishedName of the OU as argument to the -SearchBase parameter of Get-ADUser to get your report:

Get-ADOrganizationalUnit -Filter * -Properties CanonicalName | ForEach-Object {
    [pscustomobject]@{
        OUCanonicalName = $_.CanonicalName
        TotalUserCount  = @(Get-ADUser -Filter * -SearchBase $_.DistinguishedName).Count
    }
} | Export-Csv .... -NoTypeInformation
Related