I'm looking for a PowerShell script that will get me:
OU's
OU
.I have found this:
(Get-ADUser -Filter * -SearchBase “ou=Users,ou=A1,dc=contoso,dc=com”).count
This does exactly what I want, but I would have to type in each OU
name. The problem is that we have 100+ OU's
. The specific OU
I'm wanting to run this in is contoso.com\cmsg\users
under the cmsg\users
is where the 100+ OU's
reside.
I like this one - outputs exactly what original poster was after:
$root_ou = "ou=Users,ou=cmsg,dc=contoso,dc=com"
$User = get-aduser -filter * -SearchBase $ou -SearchScope Subtree | Select @{Name="OU";Expression={$_.distinguishedName -match "cn=.*?,OU=(?<OU>.*)" | Out-Null;$Matches.OU}}
$User | Group -Property OU | Select Name,Count
Output looks like this
Name Count
---- -----
Office 1,ou=Users,ou=cmsg,dc=contoso,dc=com 1230
Office 2,ou=Users,ou=cmsg,dc=contoso,dc=com 390
Office 3,ou=Users,ou=cmsg,dc=contoso,dc=com 90
Office 4,ou=Users,ou=cmsg,dc=contoso,dc=com 10
To find the DistinguishedName of the root_ou you're after:
Get-ADOrganizationalUnit -Filter 'Name -like "*"' | Format-Table Name, DistinguishedName -A
Here is the PowerShell command to Get a count of users in a specific OU.
(Get-ADObject -Filter * -SearchBase "path of your OU").Count
I propose you come at this from another angle. Each ad user contains information about its parent container. Since you are already returning all users. Lets use that to determine the counts. Caveat being that if you have user-less OU's they would not show in the results.
Get-ADUser -Filter * -Properties CN |
Select-Object @{Label='ParentContainer';Expression={$_.Distinguishedname -replace "CN=$($_.cn),"}} |
Group-Object -Property ParentContainer |
Select-Object Name,Count
You can of course still use -SearchBase
to narrow the scope of Get-ADUser
.
If this is not what you wanted your next solution would require output from Get-ADOrganizationalUnit.
$ous = Get-ADOrganizationalUnit -Filter * -SearchBase "ou=Users,ou=CMSG,dc=contoso,dc=com" | Select-Object -ExpandProperty DistinguishedName
$ous | ForEach-Object{
[psobject][ordered]@{
OU = $_
Count = (Get-ADUser -Filter * -SearchBase "$_").count
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With