views:

9

answers:

0

--Update--

I've continued to look into this issue but have had little luck. The only work around I've found was to create a function which uses reflection to grab the private field that stores the password from the underlying DirectoryEntry object in the PrincipalContext, which I then use to create a new PrincipalContext with the same credentials as the previous entry.

Public Function GetPassword(ByVal ctx As PrincipalContext) As String
    'get the password from the field'
    Dim pwd As Object = GetType(PrincipalContext).InvokeMember("password", BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.GetField Or BindingFlags.Instance, Nothing, ctx, Nothing)

    Return pwd.ToString()
End Function

--Original Post--

I am using System.DirectoryServices.AccountManagement to work with Active Directory. I have a helper class, ADConnection, which helps speed up many of my more common tasks. On class instantiation a PrincipalContext instance is created which all of the functions in ADConnection use when communicating with the domain.

I have a function called CreateGroupInOU which accepts two parameters: Group Name (GroupName) and OU Distinguished Name (OUDN), see the code below. When creating a new group/user/or whatever using AccountManagment there is no option to create the object under any other container then the one the current context points too as far as I can tell. The code below works only because the account I am impersonating has rights to add a group to the specified OU.

What I would like to do is take the PrincipalContext created when the class was instantiated, which was created with the correct username/password anyways, and in essence copy it and point it at a new container OR find a way to specify which container to create the new object under.

Code

Public Function CreateGroupInOU(ByVal GroupName As String, ByVal OUDN As String) As GroupPrincipal
    Dim pcOU As New PrincipalContext(ContextType.Domain, Nothing, OUDN)

    Dim gpNew As New GroupPrincipal(pcOU, GroupName)
    gpNew.Save()

    Return gpNew
End Function

Thanks for the help :)