Read AD Users and Create String to Update Email Address

Hi all,

We are changing the structure of our company's email address to "firstname.lastname@ourcompany.com".  Does anyone know of code (VB.Net) that would read (loop) through our Users in Active Directory, create the new email string from First Name and Last Name in AD, then update their primary email address in Exchange Server 2003 to the new address?  Also, the old email address would need to be maintained as an alias.  We have over 1500 users worldwide, so to do this manually would be very time-consuming.  Any help is greatly appreciated.

We are Using:
Windows Server 2003
Exchange Server 2003
.Net Framework 1.1

Thanks.
LVL 4
DJDougAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mikal613Commented:
You can use the System.DirectoryServices namespace to do this:

Dim ADGroups As Object
Dim ADGroup As Object
Dim ADEntry As New DirectoryEntry("WinNT://domainname/username")

ADGroups = ADEntry.Invoke("Groups")
For Each ADGroup In ADGroups
Console.WriteLine(ADGroup.Name)
Next


then you can split the name to get the first name
0
DJDougAuthor Commented:
"Name" returns the full name.  When a tool like Dameware reads AD, it pulls First Name and Last Name, as well as the full name.  What are the fields for first name and last name? (Or, is it that obvious? lol).  Also, once I get that, how do I update the primary email address on Exchange.  Thanks.
0
ihenryCommented:
Hello DJDoug,

AD attribute for first name is Given-Name and Surname for last name.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adschema/adschema/a_givenname.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adschema/adschema/a_sn.asp

To get full name, that depends on how you create the user object. When you do that programmatically, it also depends on the type of ldap provider used to bind to AD.

To update primary email address in MS Exchange, you can make query to AD and for each user get one attribute named mail. However, mail is actually a proxyaddresses which stores multi-value of email addresses such as SMTP, x.400, etc. So your code needs to iterate the string array and find one that starts with "smtp" will be the primary address.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

DJDougAuthor Commented:
Thanks iHenry, that gets me pretty far along.  I have the following code so far which sets everything up:

        Sub Main()
            ' Add code to log each event.
            Dim RootDSE As New DirectoryServices.DirectoryEntry("LDAP://rootDSE")
            Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
            Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & DomainDN)
            Dim ADSearch As New System.DirectoryServices.DirectorySearcher(ADEntry)

            Dim ADSearchResult As System.DirectoryServices.SearchResult
            ADSearch.Filter = ("(objectClass=user)")
            ADSearch.SearchScope = DirectoryServices.SearchScope.Subtree
            Dim results As DirectoryServices.SearchResultCollection = ADSearch.FindAll()
            Dim UserFound As DirectoryServices.SearchResult
            For Each UserFound In results
                If Not IsNothing(UserFound) AndAlso Not Trim(UserFound.GetDirectoryEntry().Properties.Item("mail").Value) = "" _
                        AndAlso Not Trim(UserFound.GetDirectoryEntry().Properties.Item("givenName").Value) = "" AndAlso Not Trim(UserFound.GetDirectoryEntry().Properties.Item("sn").Value) = "" Then
                    Console.WriteLine("Name: " & UserFound.GetDirectoryEntry().Properties.Item("displayName").Value & " ")
                    Debug.WriteLine("Name: " & UserFound.GetDirectoryEntry().Properties.Item("displayName").Value & " ")

                    Dim oldEmail As String = UserFound.GetDirectoryEntry().Properties.Item("mail").Value.ToString().ToLower()
                    Console.WriteLine("Current Email: " & oldEmail)
                    Debug.WriteLine("Current Email: " & oldEmail)

                    Dim firstName As String = UserFound.GetDirectoryEntry().Properties.Item("givenName").Value.ToString().ToLower()
                    Dim lastName As String = UserFound.GetDirectoryEntry().Properties.Item("sn").Value.ToString().ToLower()
                    Dim newEmail As String = firstName & "." & lastName & "@mycompany.com"
                    Console.WriteLine("New Email: " & newEmail)
                    Debug.WriteLine("New Email: " & newEmail)

                    If oldEmail <> newEmail Then
                        ' Code here to update Exchange Server.
                        ' Need help with this part.
                    End If

                    Console.WriteLine(vbCrLf)
                    Debug.WriteLine(vbCrLf)
                End If
            Next
        End Sub

Can you help with the Exhange updating code, or point me to an article that can explain?  Also, I need to make sure that once I update the smtp with new email address, that the old email address is added as an alias.  Where do I add the alias?  Also, additional 250 points is added for this question (750 total).  Thanks.
0
ihenryCommented:
I think we're getting closer here..

this is the part to update the primary email address

' inside the loop...
Dim deUser As DirectoryEntry = UserFound.GetDirectoryEntry()

' if the user account has first name, last name and full name specified
If String.Format("{0}{1}{2}", givenName, sn, displayName).Trim().Length > 0 Then

   ' the new email address
    Dim newEmail As String = String.Format("{0}.{1}@mycompany.com", givenName, sn)

    If deUser.Properties.Contains("mail") Then
      ' mail is multi-value attribute, you need to handle it differently
      If deUser.Properties.Contains("mail") Then
          Dim propertyValues As PropertyValueCollection = deUser.Properties("mail")
          If Not IsNothing(propertyValues) Then
            Dim values As New ArrayList
            values.AddRange(propertyValues)
            Dim oldMail As String
            For Each m As String In values
                If m.ToLower().StartsWith("smtp") Then
                  ' primary email address
                  oldMail = m.Substring(4)
                End If
            Next
            values.Remove(oldMail)
            If oldMail.Length > 0 And Not oldMail.Equals(newMail) Then
                deUser.Properties("mail").Clear()
                deUser.Properties("mail").AddRange(values.ToArray())
                deUser.CommitChanges()
            End If
          End If
      End If
    End If
End If
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ihenryCommented:
mm..forgot something

If oldMail.Length > 0 Then
    values.Remove(oldMail)
    values.Add("smtp:" + newEmail)
    deUser.Properties("mail").Clear()
    deUser.Properties("mail").AddRange(values.ToArray())
    deUser.CommitChanges()
End If


0
DJDougAuthor Commented:
Will this keep the old mail as an alias?
0
ihenryCommented:
mm..nope sorry, forgot your requirement

comment out this line
values.Remove(oldMail)
0
DJDougAuthor Commented:
Thanks ihenry!  That works perfect.  Saved many, many hours of manual updates.  Really appreciate that.  ...I had posted another 250 points earlier for this question.  Please post a generic comment in that question and I will give you those points as well.  Thanks again.  Here's the other question:

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_21201627.html

DJ Doug
0
ihenryCommented:
You're welcome DJ Doug, glad could help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.