List OUs via PowerShell / Nudge needed

Posted on 2011-10-05
Medium Priority
Last Modified: 2012-05-12

I have the following script (posted in the code block below), and am attempting to have PowerShell list OUs...  But I haven't been successful.

Would anybody happen to be able to point me in the right direction?
$strFilter = "(&(objectCategory='organizationalUnit'))"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"

$colProplist = "name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()

foreach ($objResult in $colResults)
    {$objItem = $objResult.Properties
        $OUName = $objItem.name

         Write-Host $OUName

Open in new window

Question by:usslindstrom
  • 2
  • 2
  • 2
  • +1
LVL 21

Expert Comment

by:Hendrik Wiese
ID: 36922568

Accepted Solution

LindyS earned 668 total points
ID: 36922586
If you have the Quest Active Roles snapin, you can run this simple command.

Get-QADObject -type organizationalunit -searchroot 'Domain/OU' | Select Name,ParentContainer | Export-CSV OU_Listing.csv -notype
LVL 21

Assisted Solution

by:Hendrik Wiese
Hendrik Wiese earned 668 total points
ID: 36922587
This will export the data to C:\temp\ngtest.csv

# Initialize array with two fields:
# Distribution group, Members
$totalObj = @()
# Retrieve all DGs
$temp = Get-DistributionGroup -ResultSize Unlimited |  


       # Loop through all distribution groups
       ForEach-Object {           


             # Add the members of the DG to an array
             [array]$mem = Get-DistributionGroupMember -id $_      


             # Loop through the DG and assign each member name to the variable $member
             for ($i = 0; $i -lt $mem.Count; $i++) {
                    $member = $mem[$i].name

                    # Create instance of object of type .NET
                    $obj = New-Object System.Object

                    # Add the name of the DG to the object
                    $obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force

                    # Add the member name to the object
                    $obj | Add-Member -MemberType NoteProperty -Value $member -Name 'Members' -Force -PassThru

                    # Add the object to the array
                    $totalObj += $obj

# Pipe output to .csv file
$totalObj | Export-Csv -Encoding 'Unicode' c:\temp\ngtest.csv
The output is written like this to the csv. file:
"Distribution Group",Members
"All Users","Jon-Alfred Smith"
"All Users","Julie Smith"
"Windows SBS Administrators","Standard User with administration links"
"Windows SBS Administrators","Jon-Alfred Smith"

If you just want to have the name of the DG once, change this line: Only add the name the first time, when the counter is zero:
# Add the name of the DG to the object
if ($i -eq 0) {
$obj | Add-Member -MemberType NoteProperty -Value $_.Name -Name 'Distribution Group' -Force

Open in new window

What Security Threats Are We Predicting for 2018?

Cryptocurrency, IoT botnets, MFA, and more! Hackers are already planning their next big attacks for 2018. Learn what you might face, and how to defend against it with our 2018 security predictions.

LVL 11

Assisted Solution

marek1712 earned 664 total points
ID: 36923461
Not necessarily the fastest and optimized way:
Import-Module ActiveDirectory
cd "dc=your,dc=domain"
# The easiest way (very UNOPTIMIZED). It'll browse through whole Directory, and then will check the objectClass property:
Get-ChildItem -Recurse | Where-Object {$_.objectClass -eq "organizationalUnit"} | Select-Object Name, distinguishedName | Export-Csv c:\out.txt

Open in new window


Author Comment

ID: 36928012
Thanks for the suggestions so far guys.

HendrikWiese, much appreciated on that code.  Group Membership was going to be my next task.  For this one though, I'm needing to just work with the OUs in AD.

LindyS & marek1712, thank you very much for the versions of code you guys provided.  It's exactly what I was needing.  But I have two questions if you wouldn't mind.

1.  I'd like to keep this in native PowerShell, without having to load any additional PS Modules.  These both get me what I need, but my goal is to be able to run this on units that don't have things like Qwest AD PowerShell extensions, etc.

2.  Both versions of scripts that you guys gave me are recursive.  They work great, but would you happen to know how I could just have it spew out a list of OUs at the root of where I'm targeting, and not Sub-OUs?

Thanks for everything so far guys, I really do appreciate the help.

Expert Comment

ID: 36928623
The easiest way to do that, if you don't want to use any snapins, would be simply to use ADUC.
Right click on the parent container and choose export list. It will provide you with a list of all OU's under that in either a txt or csv format. You can add or remove columns to provide what details you need.

If you decide to use Active Roles, it is a free download, and you don't need the server to use the shell.
The download link is;

Author Closing Comment

ID: 36928700

Thank you all for your assistance here.  The information is very valuable.
LVL 11

Expert Comment

ID: 36928903
usslindstrom - I prefer not to use external PowerShell snap-ins too.
ActiveDirectory module is a native one (from Microsoft) and can be found either on domain controllers or workstations with RSAT installed. Nothing else is required.
If you want to get rid of SubOUs - the remove the "-Recurse" switch. You'll have to modify the second step though.

Featured Post

Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A brief introduction to what I consider to be the best editor for PowerShell.
In this post, I will showcase the steps for how to create groups in Office 365. Office 365 groups allow for ease of flexibility and collaboration between staff members.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Screencast - Getting to Know the Pipeline

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question