Shell – Get only user OU from Active Directory Using Powershell/CLI

active-directorypowershell

I want to get only OU of specific user.

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

USERNAME = OU_NAME

Best Answer

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.

Related Question