2

The I wrote the below script to return the name of all the Organisational Units in the domain that are empty.

I would like the script to also tell me the total number of empty OU's at the end, by counting the lines returned. I've tried assigning an $array to the New-Object, and adding various versions of $array.count or | Measure-Object at the end of the script, but all return 0.

Get-ADOrganizationalUnit -Filter * |
foreach {
    $o = Get-ADObject -filter * -searchbase $_.distinguishedname -searchscope 1
    $total = ($o | Measure-Object).Count 
    New-Object psobject -Property @{
        Name=$_.distinguishedname
        } |
        where-object {$total -le "0"}
    }

1 Answer 1

4
$ou = Get-ADOrganizationalUnit -Filter * | 
Where-Object { -not (Get-ADObject -SearchBase $_.DistinguishedName -Filter * -SearchScope OneLevel) }


# get the count
$ou|measure

$list OUs
$ou 
Sign up to request clarification or add additional context in comments.

2 Comments

As always, you do the job in half the code, and your answer is right on the money, so I'll be accepting this as the answer. However, I didn't expect it to be so good. See I wanted to keep some flexibility in the script, in case my colleagues wanted to look for OU's that only had a couple of objects in an OU. Is there a way to keep the -le "0", or similar in the script so the so the number of objects searched for can be changed?
Thanks, I geuss you can do: where{ @(Get-ADObject -SearchBase $_.DistinguishedName -Filter * -SearchScope OneLevel).Count -le $number}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.