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"
- ADObject: Specifies the object (e.g. user account, computer name etc.) you want to search.
- ADObjectLists: Specifies list of account name you want to import.
- Server: Specifies the servers on which the command runs.
- Credential: Specifies a user account that has permission to perform this action.
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
powershell
$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"}
$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