Discovering a users OU

Interesting question – how do you discover the OU in which an AD user is sitting?  The Quest cmdlets were very helpful because they had a ParentContainer property. With the Microsoft cmdlets you have to do a bit of work

There are two places to look – the distinguished name and the canonical name

PS> $user = Get-ADUser -Identity Richard -Properties Canonicalname
PS> $user

CanonicalName     : Manticore.org/Users/Richard
DistinguishedName : CN=Richard,CN=Users,DC=Manticore,DC=org
Enabled           : True
GivenName         : Richard
Name              : Richard
ObjectClass       : user
ObjectGUID        : b94a5255-28d0-4f91-ae0f-4c853ab92520
SamAccountName    : Richard
SID               : S-1-5-21-3881460461-1879668979-35955009-1104
Surname           :
UserPrincipalName :
Richard@Manticore.org

Notice the different formats

The distinguished name is easiest

PS> ($user.DistinguishedName -split ",", 2)[1]
CN=Users,DC=Manticore,DC=org

use split on the DistinguishedName.  Note the format of the split command  - - - ",", 2

It means split on a comma and give me two elements – one containing the data before the first comma & the second containing all data after the first comma

The canonical name needs a bit more work

PS> $elements = $user.CanonicalName -split '/'
PS> $elements[0..($elements.Count - 2)] -join '/'
Manticore.org/Users

split the canonical name on ‘/’ and then recreate the string dropping the last element

One Response to Discovering a users OU

  • Hi Richard,

    Regex versions (aka “Cat walked on keyboard”:-)

    PS:\> “CN=Richard,CN=Users,DC=Manticore,DC=org” -replace ‘^.*?,’
    CN=Users,DC=Manticore,DC=org

    PS:\> “Manticore.org/Users/Richard” -replace ‘/[^/]*$’
    Manticore.org/Users

    Cheers,
    Chris

Leave a Reply