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     :
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 :

Notice the different formats

The distinguished name is easiest

PS> ($user.DistinguishedName -split “,”, 2)[1]

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 ‘/’

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

This entry was posted in PowerShell and Active Directory. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s