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

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
5,906 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,381 questions
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. SChalakov 10,261 Reputation points MVP
    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 1 Reputation point
    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 )}

    0 comments No comments

  3. 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.

    0 comments No comments