views:

328

answers:

1

Does anyone know what property I can query for in an ADSI query that would return the object's parent OU? I know I can bind to the AD object and then use object.Parent to return it's parent OU, but if I ask for "parent" in a ADSI query it returns back as a invalid query I would rather not do bind unless absolutely necessary.

(i.e. "SELECT sAMAccountName, distinguishedName, objectSid, groupType FROM 'LDAP://DC=Contoso,DC=COM' WHERE objectCategory='group'")

A: 

Look at the distinguishedName property, and discard anything before the first delimiting comma. That will be the distinguishedName of the parent object (which may not be an OU by the way, it could potentially be a container or other type of object)

Here's a function to get the parent distinguishedName from a child distinguishedName. It handles distinguishedName values that contain escaped commas. public string GetParent(string sDistinguishedName) { int iPos = sDistinguishedName.IndexOf(',');

    if (iPos > 0)
    {
        while (iPos > -1)
        {
            //go back from iPos to find all slashes.
            int iFound = 0;
            for (int iSearch = iPos - 1; iPos >= 0 && sDistinguishedName[iSearch] == '\\'; iSearch--)
            {
                iFound++;
            }

            if (iFound % 2 == 0)
            {
                return sDistinguishedName.Substring(iPos + 1, sDistinguishedName.Length - iPos - 1);
            }
            else
            {
                iPos = sDistinguishedName.IndexOf(',', iPos + 1);
            }
        }
    }

    return sDistinguishedName;
}
Jeremy