Search code examples
c#active-directorydirectoryservices

How do I set the ManagedBy property on a GroupPrincipal


I'm creating and updating Groups in Active Directory using the GroupPrincipal class in System.DirectoryServices.AccountManagement. When creating and updating, I also need to be able to set the ManagedBy property that you are able to set in the Managed By tab in the groups properties in the AD management console.

Can it be done programatically?


Solution

  • You cannot do this directly, unfortunately - but you can get access to the underlying DirectoryEntry and do it there:

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
    
    UserPrincipal toBeModified = UserPrincipal.FindByIdentity(".....");
    UserPrincipal manager = UserPrincipal.FindByIdentity(ctx, "......");
    
    DirectoryEntry de = toBeModified.GetUnderlyingObject() as DirectoryEntry;
    
    if (de != null)
    {
        de.Properties["managedBy"].Value = manager.DistinguishedName;
        toBeModified.Save();
    }