Retrieve Display names of Contacts/Users whose email id's are in a txt file.

Hi,

Retrieve Display names of Contacts/Users whose email id's are in a txt file.
I have a txt file that has 100's of email addresses. i want to query with AD and get the display name of the email id and the Ou name alone into a txt file
Email address;Display name;Ou name
Can anyone help with this.

Regards'
Sharath
LVL 11
bsharathAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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.

SiliconXPCommented:
try this in C#. Add the code to load your text file and call the function at the right place
GetUserProperty("<myaccount>", "DisplayName");//how to use the function

public static string GetUserProperty(string accountName, string propertyName)
{
        DirectoryEntry entry = new DirectoryEntry();
        // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
        entry.Path = "LDAP://...";
        entry.AuthenticationType = AuthenticationTypes.Secure;

        DirectorySearcher search = new DirectorySearcher(entry);
        search.Filter = "(SAMAccountName=" + accountName + ")";
        search.PropertiesToLoad.Add(propertyName);

        SearchResultCollection results = search.FindAll();
        if (results != null && results.Count > 0)
        {
                return results[0].Properties[propertyName][0].ToString();
        }
        else
        {
                return "Unknown User";
        }
}

Open in new window

bsharathAuthor Commented:
Thanks
How do i run the script
markdmacCommented:
Here is a VBScript solution that will do it.
'==========================================================================
'
' NAME: GetDisplayNamesFromEmailAddress.vbs
'
' AUTHOR: Mark D. MacLachlan , The Spider's Parlor
' URL: http://www.thespidersparlor.com
' DATE  : 04/21/2010
' COPYRIGHT 2010 The Spider's Parlor, All Rights Reserved
'
'    THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
'    ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
'    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
'    PARTICULAR PURPOSE.
'
'    IN NO EVENT SHALL THE SPIDER'S PARLOR AND/OR ITS RESPECTIVE SUPPLIERS 
'    BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
'    DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
'    WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
'    ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
'    OF THIS CODE OR INFORMATION.
'
'
' COMMENT: 
' Finds Display Name From Email Addresses
' Example file:
' forest@bubbagump.com
' bubba@bubbagump.com
' sgtdan@bubbagump.com
'=====================================

reportFilePath = "c:\ParlorTricks\Report.txt"
sourceFilePath = "c:\ParlorTricks\UserList.txt"



'*************************************************
' Do Not edit below this line
'*************************************************

Const ForWriting = 2

'open the file system object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set WSHShell = CreateObject("wscript.shell")
'open the data file
Set oTextStream = oFSO.OpenTextFile(sourceFilePath)
'make an array from the data file
UserList = Split(oTextStream.ReadAll, vbNewLine)
'close the data file
oTextStream.Close


For Each Email In UserList
	displayName = SearchDisplayName(Email)
	Report = Report & Email & ";" & displayName & vbCrLf
Next

Set reportFile = oFSO.CreateTextFile(reportFilePath, ForWriting)
reportFile.write Report
WSHShell.Run "Notepad.exe " &  reportFilePath


Public Function SearchDisplayName(vSAN)
    Dim oRootDSE, oConnection, oCommand, oRecordSet
    Set oRootDSE = GetObject("LDAP://rootDSE")
    Set oConnection = CreateObject("ADODB.Connection")
    oConnection.Open "Provider=ADsDSOObject;"
    Set oCommand = CreateObject("ADODB.Command")
    oCommand.ActiveConnection = oConnection
    oCommand.CommandText = "<LDAP://" & oRootDSE.get("defaultNamingContext") & _
        ">;(&(objectCategory=User)(proxyaddresses=*" & vSAN & "));displayName,canonicalName;subtree"
    Set oRecordSet = oCommand.Execute
    On Error Resume Next
    CanName =  Join(oRecordSet.Fields("canonicalName"),"")
    OUName = Left(CanName,InStrRev(CanName,"/")-1)
    SearchDisplayName = oRecordSet.Fields("displayName") & ";" & OUName
    On Error GoTo 0
    oConnection.Close
    Set oRecordSet = Nothing
    Set oCommand = Nothing
    Set oConnection = Nothing
    Set oRootDSE = Nothing
End Function

Open in new window

CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

bsharathAuthor Commented:
Perfect mark can i get just the Ou name. Say 2 level if possible or just 1
RootOU\ChildOU
markdmacCommented:
That won't be as accurate since you can have duplication of names that way.  But yes...
'==========================================================================
'
' NAME: GetDisplayNamesFromEmailAddress.vbs
'
' AUTHOR: Mark D. MacLachlan , The Spider's Parlor
' URL: http://www.thespidersparlor.com
' DATE  : 04/21/2010
' COPYRIGHT 2010 The Spider's Parlor, All Rights Reserved
'
'    THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
'    ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
'    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
'    PARTICULAR PURPOSE.
'
'    IN NO EVENT SHALL THE SPIDER'S PARLOR AND/OR ITS RESPECTIVE SUPPLIERS 
'    BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
'    DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
'    WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
'    ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
'    OF THIS CODE OR INFORMATION.
'
'
' COMMENT: 
' Finds Display Name From Email Addresses
' Example file:
' forest@bubbagump.com
' bubba@bubbagump.com
' sgtdan@bubbagump.com
'=====================================

reportFilePath = "c:\ParlorTricks\Report.txt"
sourceFilePath = "c:\ParlorTricks\UserList.txt"



'*************************************************
' Do Not edit below this line
'*************************************************

Const ForWriting = 2

'open the file system object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set WSHShell = CreateObject("wscript.shell")
'open the data file
Set oTextStream = oFSO.OpenTextFile(sourceFilePath)
'make an array from the data file
UserList = Split(oTextStream.ReadAll, vbNewLine)
'close the data file
oTextStream.Close


For Each Email In UserList
	displayName = SearchDisplayName(Email)
	Report = Report & Email & ";" & displayName & vbCrLf
Next

Set reportFile = oFSO.CreateTextFile(reportFilePath, ForWriting)
reportFile.write Report
WSHShell.Run "Notepad.exe " &  reportFilePath


Public Function SearchDisplayName(vSAN)
    Dim oRootDSE, oConnection, oCommand, oRecordSet
    Set oRootDSE = GetObject("LDAP://rootDSE")
    Set oConnection = CreateObject("ADODB.Connection")
    oConnection.Open "Provider=ADsDSOObject;"
    Set oCommand = CreateObject("ADODB.Command")
    oCommand.ActiveConnection = oConnection
    oCommand.CommandText = "<LDAP://" & oRootDSE.get("defaultNamingContext") & _
        ">;(&(objectCategory=User)(proxyaddresses=*" & vSAN & "));displayName,canonicalName;subtree"
    Set oRecordSet = oCommand.Execute
    On Error Resume Next
    CanName =  Join(oRecordSet.Fields("canonicalName"),"")
    OUName = Left(CanName,InStrRev(CanName,"/")-1)
    OUName = Right(OUName,Len(OUName)-InStrRev(OUName,"/"))
    SearchDisplayName = oRecordSet.Fields("displayName") & ";" & OUName
    On Error GoTo 0
    oConnection.Close
    Set oRecordSet = Nothing
    Set oCommand = Nothing
    Set oConnection = Nothing
    Set oRootDSE = Nothing
End Function

Open in new window

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
Meir RivkinFull stack Software EngineerCommented:
here's the code snippet.
it reads c:\temp\mail.txt for a list of emails (line by line), then query the AD for users with this email and logd results to c:\temp\output_file.txt.

the output file should look something like this:

User account(s) with the specified email:
OU: CN=Ben Stone,CN=Users,DC=SOAP,DC=COM
Name: Ben Stone
mail: Ben.Stone@blabla.com

No user accounts found with email: jonny@gmail.com

User account(s) with the specified email:
OU: CN=Roy Robson,CN=Users,DC=SOAP,DC=COM
Name: Roy Robson
mail: Roy.Robson@blabla.com

No user accounts found with email: ziggy@hotmail.com


set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInputFile = objFSO.OpenTextFile ("C:\temp\mails.txt")
Set objOutputFile = objFSO.CreateTextFile("c:\temp\output_file.txt", True)
Do Until objInputFile.AtEndOfStream

strNextLine = objInputFile.Readline

objCommand.CommandText = _
 "<LDAP://ad2008rd/cn=users,dc=soap,dc=com>;" & _
 "(&(objectCategory=person)(objectClass=user)(mail=" & strNextLine & "));" & _
 "distinguishedName,mail,name"
 
Set objRecordSet = objCommand.Execute

If objRecordset.EOF Then
	objOutputFile.WriteLine
	objOutputFile.WriteLine "No user accounts found with email: " & strNextLine
	objOutputFile.WriteLine
Else
	While Not objRecordset.EOF
	If IsNull(objRecordset.Fields("mail")) = FALSE Then 
		objOutputFile.WriteLine "User account(s) with the specified email:"
		objOutputFile.WriteLine "OU: " & objRecordset.Fields("distinguishedName") 
		objOutputFile.WriteLine "Name: " & objRecordset.Fields("name") 
		objOutputFile.WriteLine "mail: " & objRecordset.Fields("mail") 
		objOutputFile.WriteLine
	end if	

	objRecordset.MoveNext
	Wend
End If
Loop

objConnection.Close
objInputFile.Close
objOutputFile.Close

Open in new window

bsharathAuthor Commented:
Thanks Mark works perfect
sedgwick sorry just saw your solution once accepted
Meir RivkinFull stack Software EngineerCommented:
no worries, was 2 late :)
markdmacCommented:
Sedgwick, just a comment, distinguishedName is not the OU.  It is the full LDAP path to the user object.  Canonical name is best for extracting that information as I demonstrated above.
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
Programming Languages-Other

From novice to tech pro — start learning today.