Using information from tip 7714 and tip 7717, I have scripted DN2Acct.bat to return a user's sAMAccountName, or distinguishedName, by providing their displayName.

The syntax for using DN2Acct.bat is:

DN2Acct "Display Name" \[/D\]

Where "Display Name" is the displayName value, like "Jerold Schulman", and /D is an optional parameter that outputs the user's distinguishedName instead of the default sAMAccountName.

The output is displayed on the console, but you can return it in a variable using:

<b>for /f "Tokens=*" %%u in ('DN2Acct "Display Name"') do (
 set variable=%%u
)</b>

Examples:

To return the <b>sAMAccountName</b> of Jerold Schulman:

<b>DN2Acct "Jerold Schulman"

Output:

Jerry</b>


To return the <b>distinguishedName</b> of Jennifer Schulman:

<b>DN2Acct "Jennifer Schulman" /D

Output:

CN=Jennifer Schulman,CN=Users,DC=JSIINC,DC=COM</b>


To return the <b>distinguishedName</b> of all users whose last name is Schulman:

<b>dn2acct *Schulman /d

Output:

CN=Jerold Schulman,CN=Users,DC=JSIINC,DC=COM
CN=Jennifer Schulman,CN=Users,DC=JSIINC,DC=COM</b>


To return the <b>sAMAccountName</b> of all users whose given name starts with a Je:

<b>dn2acct Je*

Output:

Jerry
Jennifer</b>
DN2Acct.bat contains:
@echo off
if \{%1\}==\{\} @echo Syntax DN2Acct "Display Name" \[/D\]&goto :EOF
setlocal
set fn=%1
set fn=%fn:"=%
set attr=sAMAccountName
if /i "%2" EQU "/d" set attr=distinguishedName
set qry=dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(displayName=%fn%))" -attr %attr% -limit 0
for /f "Skip=1 Tokens=*" %%u in ('%qry%') do (
 @echo %%u
)
endlocal