sAMAccountName在VB.NET中搜索

时间:2013-08-28 13:41:05

标签: vb.net active-directory

我对VB很新,所以我想请你帮忙。我想为此代码添加搜索功能。假设有人会搜索sAMaccountname,他会收到该用户的电子邮件。我真的不知道如何处理AD中的属性,所以只有我拥有的是这个(我认为很容易找到结果:))。当我看到如何为samaccountname发送电子邮件时,我想我也可以继续其他事情。谢谢。

Imports System.DirectoryServices
Imports System.DirectoryServices.ActiveDirectory

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim domains As DomainCollection = Forest.GetCurrentForest.Domains
        For Each domain As Domain In domains
            'MessageBox.Show(domain.Name)
            ComboBox2.Items.Add(domain.Name)
        Next
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        Dim domain As DirectoryEntry = New DirectoryEntry("LDAP://ourdomain.com/OU=Users,OU=Czech Republic,OU=TEAD,DC=eu,DC=ourcompany,DC=com")
        For Each child As DirectoryEntry In domain.Children
            ComboBox1.Items.Add(child.Name)
        Next
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

这样的事情应该做你想做的事情:

Public Shared Function FindEmailsFromSamAccountName(ByVal samAccountName As String) As String

    Dim ctx As New PrincipalContext(ContextType.Domain)

    Dim qbeUser As New UserPrincipal(ctx)
    qbeUser.SamAccountName = samAccountName
    qbeUser.Enabled = True

    Dim srch As New PrincipalSearcher(qbeUser)
    For Each foundUser In srch.FindAll
        Dim up As UserPrincipal = CType(foundUser, UserPrincipal)
        Return up.EmailAddress
    Next
    Return ""
End Function

它只返回它找到的第一个。你应该在这里添加一些错误检查。

您可以通过在samAccountName的开头或结尾添加“*”来扩展搜索以返回更多匹配,以进行通配符搜索。