VB.NET从活动目录中删除用户

时间:2010-08-06 12:44:40

标签: vb.net .net-2.0 active-directory

您好我正在尝试创建一个VB.NET应用程序,它将(希望)减少一些部门帮助台呼叫所花费的时间。我坚持的部分是如何使用VB.NET从组中删除用户。以下是我一直在玩的代码:

Public Shared Sub RemoveUserFromGroup(ByVal deUser As String, ByVal GroupName As String)
    Dim entry As DirectoryEntry = ADEntry()
    Dim mySearcher As DirectorySearcher = New DirectorySearcher(entry)

    mySearcher.Filter = "(&(ObjectClass=Group)(CN=" & GroupName & "))"
    mySearcher.PropertiesToLoad.Add("OrganizationalUnit")
    mySearcher.PropertiesToLoad.Add("DistinguishedName")
    mySearcher.PropertiesToLoad.Add("sAMAccountName")

    Dim searchResults As SearchResultCollection = mySearcher.FindAll()
    If searchResults.Count > 0 Then
        Dim group As New DirectoryEntry(searchResults(0).Path)
        Dim members As Object = group.Invoke("Members", Nothing)
        For Each member As Object In CType(members, IEnumerable)
            Dim x As DirectoryEntry = New DirectoryEntry(member)
            MessageBox.Show(x.Properties("sAMAccountName").Value)
            If x.Properties("sAMAccountName").Value = deUser Then
                MessageBox.Show(searchResults.Item(0).Path.ToString)
                MessageBox.Show(x.Properties("sAMAccountName").Value)
                'group.Invoke("Remove", New Object() {x.Properties("OrganizationalUnit").Value})
                group.Properties("member").Remove(x.Properties("OrganizationalUnit").Value)
            End If

        Next
    End If

当我运行程序时,我在group.properties行中接收到一个未处理的未指定错误的COMException。使用group.invoke时,我收到错误TargetInvocationException未处理。

我的目标是将用户名(sAMAccountName)和组名(sAMAccountName)作为字符串传递给将定位用户并将其从组中删除的函数。

我是VB.NET的新手,非常感谢人们提供的帮助。

我在.NET 2.0中进行编码,因为我不确定它所使用的服务器是否会安装3.5。

1 个答案:

答案 0 :(得分:1)

错误消息0x80004005 E_FAIL Unspecified failure不是很有帮助。在使用Active Directory时,我常常感到沮丧。

尝试换行:

group.Properties("member").Remove(x.Properties("OrganizationalUnit").Value)

group.Invoke("Remove", New Object() {x.Path.ToString()})

如果您需要更多参考,请参阅Erika Ehrli在VB.net Heaven上的这篇文章。本文介绍了Active Directory的各种用例。

我希望有所帮助。