Display what OU the objects belong to (PowerShell)

Introduction

This PowerShell Script shows what OU the objects belong to. 

Scenarios

Many users have ever asked is there any way to list what OU the objects belong to. If we provide a script can do it, obviously this could be done by scripting.​ 

Script

Step 1: Click Start, type powershell in the search box on the Start Menu, right-click the Windows PowerShell icon, and then click Run Windows PowerShell as administrator. If the User Account Control dialog box appears, confirm that the action it displays is what you want, and then click Continue.
 
Step 2: Run the script in the Windows PowerShell Console, type the one command: Import-Module <Script Path> at the prompt.
For example, type Import-Module C:\Script\ADObjectBelongsTo.psm1
This is shown in the following figure.
 
Step 3: You can type the command Get-Help Get-OSCADObjectOU -Full to display the entire help file for this function, such as the syntax, parameters, or examples.
 
Step 4:  This function contains four parameters; you can use “ADAccountName” parameter to search,for example Get-OSCADObjectOU -ADObject "Test4"
 
 
And this command will list all of listed account's OU. For example Get-OSCADObjectOU -ADObjectLists C:\List.txt
Note: Before you run the command, you need to prepare a list file. It contains some of information about the objects you want to search.
 
The results are shown in the following figure.
 
Here are some code snippets for your references. To get the complete script sample, please click the download button at the beginning of this page.
PowerShell
Edit|Remove
$ObjectInfo = Get-ADObject -Filter 'Name -like $Object'| Select-Object Name, ObjectClass, ` 
        @{Expression={$NewDistinguishedName = ($_.DistinguishedName).split(",")| ` 
        Select-String -CaseSensitive -Pattern "OU=";if($NewDistinguishedName -eq $null) 
                                                    {"(Default Container)"} 
                                                    else 
                                                    {@($NewDistinguishedName|Foreach{$_.Line})[0].Replace("OU=","")}};Label="Organizational Unit"}
 

Prerequisite

Windows PowerShell 2.0
Windows Server 2008 R2
Related forum threads:
http://social.technet.microsoft.com/Forums/en-US/winserverDS/thread/2db63cc5-b134-4fdc-8703-10667fbd05a8
http://social.technet.microsoft.com/Forums/en-AU/ITCG/thread/d795ea57-c6e2-4ea2-a2b3-53eec058d8b3
http://forums.techarena.in/active-directory/1211032.htm