JSI Tip 7335. How do I retrieve the distinguished name of a user?

The glossary defines distinguished name as:

A name that uniquely identifies an object by using the relative distinguished name for the object, plus the names of container objects and domains that contain the object. The distinguished name identifies the object as well as its location in a tree. Every object in Active Directory has a distinguished name. A typical distinguished name might be


This identifies the MyName user object in the microsoft.com domain.

Using dsquery, I have scripted GetDN.bat to return the distinguished name (DN) of a user, by using their SamID (A user account name, sometimes referred to as the user logon name), like Jerry, or the %UserName% environment variable.

The syntax for using GetDN.bat is:

call GetDN SamID DN

where DN is a call directed environment variable that will contain the DN of the SamID. If the SamID is NOT found, DN will be set to N.

Examples of usage:

call GetDN Jerry DN

returns a DN of "CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=COM" in the JSIINC.COM domain.

call GetDN "%UserName%" DN

returns a DN of "CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=COM" when I am the logged on user.

GetDN.bat contains:

@echo off
if \{%2\}==\{\} @echo Syntax: GetDN SAMID DN&goto :EOF
set dn=N
for /f "Tokens=*" %%u in ('dsquery user -samid %1') do set dn=%%u
endlocal&set %2=%dn%
NOTE: see How do I retrieve a user's distinguished name by using their User Principal Name (UPN)?

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.