Home » PowerShell » Get AdUser Parent OU

Get AdUser Parent OU

Get-AdUser cmdlet in PowerShell gets one or more active directory users based on search criteria. Get AdUser object parent contained within the distinguished name property of active directory user.

For example, CN=Arons, OU=HR, DC=SHELLPRO, DC=LOCAL here OU=HR, DC=SHELLPRO, DC=LOCAL is the parent container path of the active directory object.

In this article, we will discuss how you can get aduser parent OU using the PowerShell script and get aduser parent OU from a distinguished name.

Get AdUser Parent OU

Using Get-ADUser cmdlet in PowerShell, you can find the parent OU from given below command

$adUser = "Arons"
$dname = (Get-ADUser -Identity $adUser -Properties DistinguishedName).DistinguishedName

# Get parent OU from distinguished name
$parentOU = $dname.split(',',2)[1]

In the above PowerShell script,

Get-AdUser cmdlet gets active directory user identified by SamAccountName and gets the distinguished name of aduser.

In the next command, it splits distinguishedname to get parent OU for ad object.

The output of the above command is given below

Get AdUser Parent OU
Get AdUser Parent OU

PowerShell Tip: How to check the existence of an aduser using ErrorAction!

Get Parent OU from DistinguishedName

In the above example, it gets parent OU from a SAMAccountname.

In this example, we will extract parent OU from distinguishedname using different ways as given below

Let’s consider an example, active directory user distinguished name as given below

CN=Tom Smith,OU=SALES,DC=SHELLPRO,DC=LOCAL

Let’s find out the parent OU container path from distinguishedname as given below

# using Substring to get parent OU for adobject
$userDistName = "CN=Tom Smith,OU=SALES,DC=SHELLPRO,DC=LOCAL"
$userDistName.Substring($userDistName.IndexOf('OU='))

# Get Parent OU using ADSI 
(([ADSI]"LDAP://$userDistName").parent).Substring(7)

# using Split over aduser distinguishedname to get parent OU
$userDistName.split(',',2)[1]

In the above PowerShell script,

The first solution to get the parent container path for the aduser object is using the substring method. It uses aduser distinguishedname property and finds indexof ‘OU’ to get parent OU.

The second solution is using ADSI to get parent OU from distinguishedname of aduser object.

The third solution is using the split method over aduser distinguishedname to get the parent container path.

The output of the above commands is given below

PowerShell Get Parent OU from DistinguishedName
PowerShell Get Parent OU from DistinguishedName

PowerShell Tip: How to get aduser proxyaddresses using PowerShell!

Conclusion

I hope the above article on how to get aduser parent OU from distinguishedname is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.