I want to get only OU of specific user.

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

USERNAME = OU_NAME 
2

5 Answers

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

This works for me:

$user = Get-ADUser -Identity [USERNAME] -Properties CanonicalName $userOU = ($user.DistinguishedName -split ",",2)[1] 

Source:

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

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]

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy