How to retrieve all empty OU in all my AD

Mohamed SAKHO 1 Reputation point
2020-08-05T13:56:23.88+00:00

Hi all

I would like to know all empty OU existing on my AD.
I found a powershell command line below which retrieve this information:

Get-ADOrganizationalUnit -Filter * | ForEach-Object {
if (-not (Get-ADObject -SearchBase $_ -SearchScope OneLevel -Filter *))
{
$.Name +";;;;;;;;;;;;;;;;;;;;;;;;;"+$.DistinguishedName
}
}

This command works but it's not optimal. for example I would like to export to csv file with "export-csv -path filename.csv" and it doesn't work.
Idon't feel comfortable with powershell..
Does someone can help me to improve this script and export it. Or maybe somebody has something better in what I need?
Thank you by advance.

Mohamed

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. SChalakov 10,576 Reputation points MVP Volunteer Moderator
    2020-08-20T11:59:55.82+00:00

    Hi @SAKHO Mohamed (Externe) ,

    This can be easily solved, you have missed a "*" in front of "-Filter" (2x). Please try it like that:

    Get-ADOrganizationalUnit -Filter * | Where-Object {-not ( Get-ADObject -Filter * -SearchBase $_.Distinguishedname -SearchScope OneLevel -ResultSetSize 1 )}  
    

    This will help you find the empty OUs.

    Regards

    ----------

    (If the reply was helpful please don't forget to upvote or accept as answer, thank you)

    3 people found this answer helpful.
    0 comments No comments

  2. Klaus Bilger 81 Reputation points
    2020-08-05T14:17:26.1+00:00

    i guess you can try this

    Get-ADOrganizationalUnit -Filter * |
    Where-Object {-not ( Get-ADObject -Filter * -SearchBase $_.Distinguishedname -SearchScope OneLevel -ResultSetSize 1 )}

    1 person found this answer helpful.
    0 comments No comments

  3. Young Yang (Shanghai Wicresoft Co,.Ltd.) 661 Reputation points
    2020-08-20T01:47:31.573+00:00

    Hi, given that this post has been quiet for a while, this is a quick question and answer. Has your question been solved? If so, please mark it as an answer so that users with the same question can find and get help.
    :)

    0 comments No comments

  4. SAKHO Mohamed (Externe) 1 Reputation point
    2020-08-20T09:36:54.163+00:00

    Hi,

    sorry for the late I was in holidays, that's why I didn't answered.
    I tryied the command line but it doesn't work:

    19142-image.png
    19059-2020-08-20-11-35.png

    Thank you by advance.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.