20

On Windows XP in an Active directory environment - what is the easiest way for me to query a user's email address from AD given their username on the command line.

(Assuming I know where it is kept normally in tree).

(I know about net user loginname /domain but I just want the email address element back.)

1
  • 3
    Please note that if you are in a complex Exchange the "mail" attribute may not be the email address you're looking for. You will also need to look at the multi-valued attribute "proxyAddresses" on the user object. Jun 17, 2009 at 14:15

11 Answers 11

20
dsquery user -name "user name"|dsget user -samid -email -display 
2
  • Missed it by that much... :)
    – TheCleaner
    Jun 17, 2009 at 13:23
  • 1
    Ok - perhaps I wasn't clear - but you're close enough - what I guess I wanted was: dsquery user -samid "loginname" |dsget user -email
    – Hawkeye
    Jun 18, 2009 at 1:09
7

dsquery user -name "Firstname Lastname" | dsget user -email

6

If the email that you want is also the User Principal Name, you can get it with

whoami /upn

However, this only works to get the email of the current user, not any user as the question originally postulated.

3
  • Used this method by running cmd as the target user. Worked like a charm
    – Daniel
    Jan 12, 2016 at 19:26
  • 1
    This also only returns the UPN, which is not necessarily the same as the user's default public email address, especially if the AD domain is .local or something similar rather than a registered public domain. Oct 16, 2017 at 16:46
  • 1
    @Craig The first sentence of my answer says that...
    – krispy
    Oct 17, 2017 at 20:27
5

something like this dsquery might work.

query email by username dsquery.exe * -filter "(&(objectClass=user)(!(objectClass=computer)(sAMAccountName=username)))" | dsget user -email

I misread the post first and thought you wanted user name from email name. That's why i posted this one. dsquery.exe * -filter "(&(objectClass=user)(!(objectClass=computer)([email protected])))" -attr username

based on some scripts at work and this site which has some other ideas http://www.petri.co.il/forums/showthread.php?t=18464 about using csvde.exe

4

adfind -sc u:"username" mail

1
  • Thats a realyl useful tool, although it would be more awesome if the person supplied the source code. May 4, 2011 at 20:53
2

Install Powershell, and the QuestAD addon pack. Then it is something like:

connect-qadservice
(get-qaduser 'bobsusername').emailAddress
2

You can write simple VBScript to query thru LDAP Create a file with VBS extension

Put inside something like this

On Error Resume Next
Set objUser = GetObject _
  ("LDAP://CN=USER NAME,DC=DOMAIN_NAME,DC=com")

objUser.GetInfo

strMail = objUser.Get("mail")

WScript.echo "mail: " & strMail 

Put correct USER NAME into LDAP query string, run VBS file and enjoy :)

If it is your first time you work with LDAP, it could be a little bit complicated to write LDAP query In order to recognize the LDAP path to the user (i.e. what you need to put after LDAP://) you may download Active Directory Explorer from Microsoft Run explorer, navigate to the user and see what it shows in the Path text box

In my case it was something like CN=[user name],CN=Users,DC=[city_name],DC=[company_name],DC=com,

2

LINQ to everything! For convenience:

1) In query properties of LinqPad, add a reference to System.DirectoryServices.AccountManagement.dll. 2) Additional Namespace Import: System.DirectoryServices.AccountManagement

using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "MyDomain))
  using(UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MyUserID"))
        usr.Dump();
2

Found this thread that helped me get what I wanted. To get any AD users attributes into environment variables. This script takes all wanted attributes from logged in user and sets a corresponding environment variable. I prefixed the variables but that is optional, so variable name becomes "AD[attribute name]". Attributes is of your choice, just add or remove your attribute after -attr. Not very useful for multivalue-attributes though. Last (one) value goes into the environment variable.

This script is local to current cmd.exe

for /F "tokens=1,* delims=: " %%A in ('dsquery * domainroot -l -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=%USERNAME%))" -attr adminDescription employeetype company department physicalDeliveryOfficeName street title mail') do set AD%%A=%%B

To get global environment variables in windows we can use "setx" in windows 7. (For loginscript perhaps... but much slower.)

for /F "tokens=1,* delims=: " %%A in ('dsquery * domainroot -l -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=%USERNAME%))" -attr adminDescription employeetype company department physicalDeliveryOfficeName street title mail') do set AD%%A=%%B& setx AD%%A "%%~B" > NUL

:EDIT: a space character at end of set-statement in example 2 caused value to end with empty space. Removed it to correct. ( Set %%A=%%B& setx... ) Also found out that you must export at least two attributes for script to work properly.

A late responce, but if it can help anyone out there I'm happy.

1

I don't know it's matched to the thread starter mean or not. But I just find a solution of my existing problem that was already solved after browse this thread. Finding USER LOGIN ID based on KNOWN MAIL ADDRESS. :)

C:\Users\MrCMD>for /f "delims=" %u in ('type salesforce-uid-mail-address.txt') do @dsquery.exe * -filter "(&(objectClass=user)(!(objectClass=computer)(mail=%u)))">>"salesforce-uid-cn.txt"
┌─────────────────────────────────────┐
│ Executed Wed 07/10/2013  8:29:55.05 │ As [MrCMD]
└─────────────────────────────────────┘
C:\Users\MrCMD>for /f "delims=" %u in ('type salesforce-uid-cn.txt') do @dsget.exe user %u -samid -l|find "samid" /i>>"salesforce-uid-samid.txt"
┌─────────────────────────────────────┐
│ Executed Wed 07/10/2013  8:31:56.40 │ As [MrCMD]
└─────────────────────────────────────┘

File [salesforce-uid-mail-address.txt] contains list of e-mail addresses. File [salesforce-uid-cn.txt] contains "complete CN with path". And file [salesforce-uid-samid.txt] contains "found SAMID" alias "user login name". That's all folks. Any ideas for improvement are welcome. :)

-1

Below is a batch script I wrote for something else but it can be used to find the e-mail attribute within a CN without too much issue.


:: CN Attribute Lookup Tool
::   Written by Turbo Dog
::
:: -- Purpose: A simple lookup batch script using the ldifde command.
::
:: -- It was written to translate a hashed CN with it's more human readable attribute.
::
:: -- Multi environment version
::
:: -- anything in <brackets> is something you need to fill e.g. "set servip=10.0.0.5"
::
:: -- Generic ID Version:
:: -- <ID with read access to CN and it's target attribute> will have to be made, 
:: -- careful with this as it'll need to be a generic account with a non-expiring password
:: 
::
:BEGIN
@echo off
:: - Grey background with black font -
color 70
:RESTART
cls
:: Environment choice
:: default choice (1 preproduction 2 test 3 production)
set ENVCH=3
setlocal enableextensions enabledelayedexpansion
echo  ÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜ
echo  Û CN Attribute Lookup Tool V1.0 Û
echo  ßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßß
echo. 
echo.
echo  1. PreProduction
echo  2. Test
echo  3. Production
echo.
echo  Please enter the number of the environment you wish to search and press enter or type q and press enter to quit: (3)
set /p ENVCH=
IF %ENVCH%==1 GOTO PPRODU
IF %ENVCH%==2 GOTO TESTEN
IF %ENVCH%==3 GOTO PRODUC
IF %ENVCH%==q GOTO FINISH
IF %ENVCH%==Q GOTO FINISH
IF %ENVCH%==[%1]==[] GOTO FINISH
:: PreProduction settings
:PPRODU
set envtype=PreProduction
set servip=<IP or hostname of preproduction AD server>
set servpt=<port number of preproduction AD server>
GOTO GATHER
:: Test settings
:TESTEN
set envtype=Test
set servip=<IP or hostname of test AD server>
set servpt=<port number of test AD server>
GOTO GATHER
:: Production settings
:PRODUC
set envtype=Production
set servip=<IP or hostname of production AD server>
set servpt=<port number of production AD server>
GOTO GATHER
:GATHER
:: - Gather information for job -
cls
:: - Grey background with black font -
color 70
echo  ÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜ
echo  Û CN Attribute Lookup Tool V1.0 Û
echo  ßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßß
echo  Environment - !envtype!
echo. 
echo  Copy and paste the CN and press enter (or type q and enter to quit):
set /p resource=""
IF "%resource%"=="q" GOTO FINISH
IF "%resource%"=="Q" GOTO FINISH
set resourcein=!resource!
cls
:: - Process action -
ldifde -s %servip% -t %servpt% -a <ID with read access to CN and it's target attribute> <password for ID> -d "<the container that holds the CN's to search through cn=Container,ou=DOMAIN,o=ORG>" -f output.txt -l "<target attribute to read>" -r "(cn=%resource%)"
:: pause :: only have this line active (start colons missing) during troubleshooting to see if anything is written to the output.txt file
cls
:: - Extraction of the attribute from the output file -
set resource=
for /f "delims=" %%a in (output.txt) do (
    set line=%%a
    if "x!line:~0,22!"=="<target attribute to read>: " (
        set resource="!line:~22!"
    )
)
:: - Check to see if it has worked? -
IF NOT %resource%==[%1]==[] GOTO RESULT :: Resource value has something then send to the result step otherwise default to error
:: - The error message -
:: - Black background with red font (amiga guru looking error) -
color 0C
cls
echo  ÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜ
echo  Û CN Attribute Lookup Tool V1.0 Û
echo  ßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßß
echo  Environment - !envtype!
echo.
echo  Sorry, it appears you've entered an CN that's either not for
echo  !envtype!, has not got anything in it's attribute or has been copied incorrectly!
echo.
echo  Press any key to retry.
:: - Cleanup errored output file -
del output.txt
pause >nul
GOTO GATHER
:: - The result -
:RESULT
:: - Copy result to clipboard -
echo|set/p=%resource%|clip
:: - Grey background with black font -
color 70
cls
echo  ÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜÜ
echo  Û CN Attribute Lookup Tool V1.0 Û
echo  ßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßßß
echo  Environment - !envtype!
echo. 
echo. Your submission was: "!resourcein!"
echo  The attribute is: !resource! 
echo.
echo  !resource! has been copied to the clipboard and is ready to paste.
echo.
:: - Cleanup output file -
del output.txt
:: - default to exit -
set fn=n
echo  Do you have additional resources to look up (y for yes, n for no and c to change environment)? (n):
set /p fn=""
IF %fn%==y GOTO GATHER
IF %fn%==Y GOTO GATHER
IF %fn%==c GOTO RESTART
IF %fn%==C GOTO RESTART
:FINISH
echo.
echo  Thank you, press any key to exit.
pause >nul
:: - Set CMD Shell colours back to default -
color 07
:: - The end - 
@echo off
:EOF

1
  • There's a lot of work there and the script is probably useful in the environment for which it was written, but I fail to see how it better answers the question than the other much shorter answers that do not need input of IPs and that have been up here for years (more than seven in the case of the accepted one). There are a lot more recent and unanswered questions that will appreciate a visit from you!
    – Law29
    Nov 16, 2016 at 23:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .