2014-02-23 3 views
0

C#을 사용하여 Active Directory 그룹에서 특정 사용자를 제거하려고합니다. 현재 작동하지 않지만 내 작업을 처리해야하는 코드 조각은 다음과 같습니다. 오타가이 코드 내에있는 경우 Active Directory 그룹에서 사용자 제거

public static bool RemoveUserFromGroup(string UserId, string GroupId) 
{ 
    using (var directory = new DirectoryEntry("LDAP://server")) 
    { 
     using (var dSearch = new DirectorySearcher(directory)) 
     { 
      try 
      { 
       dSearch.Filter = "(sAMAccountName=" + UserId + ")"; 
       SearchResult sr = dSearch.FindOne(); 
       System.DirectoryServices.PropertyCollection UserProperties = sr.GetDirectoryEntry().Properties; 
       if(UserProperties == null) 
        return false; 
       foreach(object Group in UserProperties["memberOf"]) 
       { 
        if(Group.ToString() == GroupId) 
        { 
         UserProperties["memberOf"].Remove(GroupId); 
         directory.CommitChanges(); 
         directory.Close(); 
         return true; 
        } 
       } 
      } 
      catch (Exception e) 
      { 
       return false; 
      } 
     } 
    } 
    return false; 
} 

실례하시기 바랍니다, 나는 슬프게도 인터넷에 액세스 할 수 없습니다 I가 개발하고있는 기계에서 복사 수동했다.

+0

[추가 및 .NET의 Active Directory 그룹에서 사용자를 제거]의 중복 가능성 (http://stackoverflow.com/questions/2143052/adding-and-removing- users-from-active-directory-groups-in-net) – har07

답변

1

Use :

public void RemoveUserFromGroup(string userId, string groupName) 
{ 
    try 
    { 
     using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "COMPANY")) 
     { 
      GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName); 
      group.Members.Remove(pc, IdentityType.UserPrincipalName, userId); 
      group.Save(); 
     } 
    } 
    catch (System.DirectoryServices.DirectoryServicesCOMException E) 
    { 
     //doSomething with E.Message.ToString(); 

    } 
} 
+0

이 방법을 사용해 보았지만 이미 작동하지 않았습니다. "지정된 매개 변수와 일치하는 주체가 없습니다"라는 메시지가 나타납니다. 디버그 모드로 들어가면 "멤버"의 수가 예외를 throw하는 것을 볼 수 있습니다. 그러나 "결과보기"를 클릭하고 결과를 확장하면 실제 그룹 멤버를 볼 수 있습니다. 비록 내가 그들을 액세스 할 수없는 것 같습니다. 어떤 아이디어? –

+6

"IdentityType.UserPrincipalName"을 "IdentityType.SamAccountName"으로 전환하여이 오류를 무시합니다. –

0
public string RemoveUserFromList(string UserID, string ListName) 
    { 
     try 
     { 
      using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "DomainName", UserName, Password)) 
      { 
       GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, ListName); 
       group.Members.Remove(pc, IdentityType.SamAccountName, UserID); 
       group.Save(); 
      } 
      return "Success"; 
     } 
     catch (Exception ex) 
     { 
      return ex.Message; 
     } 
    } 
관련 문제