Returning the OU for an object in AD

Occasionally it can be useful to know how to retrieve the parent, or OU holding an object, from Active Directory.
Perhaps the easiest way to do this is using the Parent property.

VbScript: Getting the OU for a user

Set objUser = GetObject("LDAP://CN=Chris Dent,OU=Somewhere,DC=domain,DC=example")
strParent = objUser.Parent
WScript.Echo strParent

In VbScript the value returned is a string, to get the name of the OU either connect to the object then get the name attribute or parse the name out of the string (Split, or Mid, etc). The example below shows connecting to the parent object and echoing the name.

Set objParent = GetObject(strParent) WScript.Echo objParent.Get("name")

PowerShell: Getting the OU for a user

$DN = "CN=Chris Dent,OU=Somewhere,DC=domain,DC=example"
$User = [ADSI]"LDAP://$DN"
$Parent = $User.PSBase.Parent

PowerShell is a little different, the returned value is a DirectoryEntry, that means we can directly access any other property or attribute without connecting again.

$DN = "CN=Chris Dent,OU=Somewhere,DC=domain,DC=example"
$User = [ADSI]"LDAP://$DN"
$Name = $User.PSBase.Parent.Name

Example: Getting the OU for all members of a group

These examples assume that the group path is known, no searches are involved.


Set objGroup = GetObject("LDAP://CN=Domain Admins,CN=Users,DC=domain,DC=example")
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set objFile = objFileSystem.OpenTextFile(objGroup.Get("name") & " - Members.txt", 2, True, 0)

For Each objMember in objGroup.Members
    objFile.WriteLine objMember.Get("sAMAccountName") & VbTab & _
        objMember.Get("cn") & VbTab & objMember.Parent

Set objFile = Nothing
Set objFileSystem = Nothing
Set objGroup = Nothing


The note above about Parent returning a DirectoryEntry does not apply if using the Members method in PowerShell. The object returned is a COM Object and will not work in quite the same way. This is the equivalent of the VbScript above.

$DN = "CN=Domain Admins,CN=Users,DC=domain,DC=example"
$Group = [ADSI]"LDAP://$DN"
$Group.PSBase.Invoke("Members") | Select-Object `
    @{n="sAMAccountName";e={ [__ComObject].InvokeMember("sAMAccountName", "GetProperty", $null, $_, $null) }},
    @{n="CN";e={ [__ComObject].InvokeMember("cn", "GetProperty", $null, $_, $null) }},
    @{n="Parent";e={ [__ComObject].InvokeMember("parent", "GetProperty", $null, $_, $null) }}