I've tried this a few ways and have come very, very close but no cigar.
What I need help with is creating a report that shows the number of users in each OU. I know there are several ways to do this, but each method I've tried has given me varying degrees of usability. I would really appreciate some feedback on what I can do to improve my queries.
My first attempt was creating an object table, but unfortunately my knowledge of object tables isn't that great. The output was one large table of all the child OU's and their counts, but since a lot of our child OU's have the same name it wasn't any good. It may be possible to add another member on for the parent OU, but I'm not sure how to do that.
With this same attempt I also tried Out-Host and while this did break up the mass table into individual tables I was still stuck with the child OU name issue.
$OUName_ou = Get-ADOrganizationalUnit -filter * -searchbase ‘OU=Users,DC=business,DC=com’ -SearchScope 1
$OUName = @()
foreach ($ou in $OUName_ou) {
$Query = New-Object PSObject
$Query | Add-Member -membertype NoteProperty -Name OU_Name -Value “”
$Query | Add-Member -membertype NoteProperty -Name User_Count -Value “”
$Query.OU_Name = $ou.name
$users = get-aduser -Filter * -SearchBase $ou
$numb = $users | measure
$Query.User_Count = $numb.count
$OUName += $Query
}
$OUName
My next attempt was to try just for a list view, but the output is very muddled. It generates a list that shows the drill down for each OU, but since there are other items there I receive a long list with a lot of 0 counts. Because of the list view, and the number of items, the report is difficult to get relevant data from. If I could find a way to clean up the output it would work fine for my needs. Ideally there would be a way to modify this to exclude empty OU's and specific OU's (like test groups for example) then it would work well enough. I'm positive there is an if command I could use to do it, but so far I haven't found the right syntax.
$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
}
}
You could simply get the count value before outputting the PsCustomObject and only output that if the count is greater than 0
Something like:
$ous = Get-ADOrganizationalUnit -Filter * -SearchBase "ou=Users,ou=CMSG,dc=contoso,dc=com"
$result = $ous | ForEach-Object {
$count = (Get-ADUser -Filter * -SearchBase $_.DistinguishedName).Count
if ($count) {
[PsCustomObject]@{
OU = $_.DistinguishedName
Users = $count
}
}
}
# output as table on screen
$result | Format-Table -AutoSize
# output to CSV you can open in Excel
$result | Export-Csv -Path 'D:\Test\UserCount.csv' -UseCulture -NoTypeInformation
Use [PsCustomObject]
here, because it is ordered by default