List OUs via PowerShell / Nudge needed

Experts,

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

LVL 5
usslindstromAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Hendrik WieseInformation Security ManagerCommented:
LindySCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Hendrik WieseInformation Security ManagerCommented:
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


Reference
SD-WAN: Making It Work for You

As bandwidth requirements and Internet costs grow, businesses naturally want to manage budgets by reducing reliance on their most expensive connection types. Learn more about how to make SD-WAN work for your business in our on-demand webinar!

marek1712Commented:
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

usslindstromAuthor Commented:
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.
LindySCommented:
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;
http://www.quest.com/powershell/activeroles-server.aspx
usslindstromAuthor Commented:
Understood.

Thank you all for your assistance here.  The information is very valuable.
marek1712Commented:
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.