2

I want to get only OU of specific user.

Example the command should display what OU user JOHN belongs to:

USERNAME = OU_NAME
2
  • ok got it ` $user = get-aduser ims $uo = $user.distinguishedname.substring($user.distinguishedname.indexof(",") + 1,$user.distinguishedname.Length - $user.distinguishedname.indexof(",") - 1) write-host "$($user.Name) = $uo" ` Feb 15, 2017 at 9:59
  • String parsing does not work in many AD implementations that use the , character in names. Feb 15, 2017 at 22:44

5 Answers 5

3

If you don't have the AD-Module installed, you can also use this. I found this very useful when I ran scripts where I needed AD-Information, but didn't have the AD-Module installed. :

$strFilter = "(&(objectCategory=User)(samAccountName=$env:username))"
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = $strFilter
$objPath = $objSearcher.FindOne()
$objUser = $objPath.GetDirectoryEntry()
$DN = $objUser.distinguishedName
$ADVal = [ADSI]"LDAP://$DN"
$WorkOU = $ADVal.Parent
$WorkOU

Now $WorkOU would return a string like this LDAP://OU=userou,OU=userou2,DC=internal,DC=domain,DC=com which you can filter any way you want.

0
2

This works for me:

$user = Get-ADUser -Identity [USERNAME] -Properties CanonicalName

$userOU = ($user.DistinguishedName -split ",",2)[1]

Source: http://itknowledgeexchange.techtarget.com/powershell/discovering-a-users-ou/

1
  • The weird split syntax is documented in about_split and means "split on the first comma (into at most 2 substrings) and return the second ([1]) part as the OU.
    – Nickolay
    May 8, 2020 at 5:18
1

The Get-ADPathname.ps1 script provides one very simple technique for this that doesn't require string parsing:

PS C:\> (Get-ADUser kendyer).DistinguishedName | Get-ADPathname -Format X500Parent
OU=Sales,DC=fabrikam,DC=com

(String parsing is not robust, as stated in the article.)

2
0

I used the script from Laage, but changed it slightly because we use ',' in our names. After the change it will stil work for names without ','.

$user = Get-ADUser -Identity [USERNAME]

$userOU = ($user.DistinguishedName -split "=",3)[-1]

-1

Some time the name includes a comma. The best solution I have found is this one:

$user = Get-ADUser -Identity [USERNAME] -Properties CanonicalName
$userOU = "OU="+($user.DistinguishedName -split ",OU=",2)[1]
1
  • This just copies Laage's answer from 2017.
    – TylerH
    Jun 9, 2022 at 19:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .