How to Get a User's Email from Active Directory in Batch Script
The "Email" attribute is one of the most vital communication fields in Active Directory. For IT administrators, being able to programmatically extract a user's email address via a Batch script is essential for sending automated password expiration alerts, distribution list auditing, or populating third-party databases during onboarding. While this is visible in the "General" tab of a user's properties, manual collection is impossible for hundreds of accounts. This guide explains how to use the dsget utility and the PowerShell bridge to pull email data instantly.
Why Fetch the Email Attribute?
- Automated Notifications: Sending a notification to a specific user after their computer has been successfully imaged or their software has been updated.
- Inventory Auditing: Mapping samAccountNames to real-world email identities for an annual security group review.
- Contact Directory Generation: Building a simple text-based office directory that includes every employee's primary contact address.
The dsquery and dsget utilities are part of the Remote Server Administration Tools (RSAT). These must be installed on your workstation to query Active Directory from the command line.
Method 1: Using DSGET (The Classic Way)
The dsget user command has a dedicated -email flag that returns the primary SMTP address stored in the account's metadata.
@echo off
setlocal
:: Check for RSAT tools
where dsquery >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] dsquery.exe not found. Install RSAT tools first.
echo [HELP] Settings ^> Apps ^> Optional Features ^> Add RSAT
pause
exit /b 1
)
set /p "USN=Enter username: "
if "%USN%"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)
echo [PROCESS] Retrieving primary contact for: "%USN%"...
echo.
:: 1. We find the user and pipe their identity to dsget
:: 2. We request the -email attribute
dsquery user -samid "%USN%" | dsget user -email
if %errorlevel% neq 0 (
echo [ERROR] User not found or Domain Controller is unreachable.
)
pause
Method 2: Extracting the Email Address into a Variable
To use the email in a script that sends an alert (e.g., "Send email to %USER_EMAIL%"), you must capture the string inside a FOR loop.
@echo off
setlocal
set /p "TARGET=Enter username: "
if "%TARGET%"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)
:: Check for RSAT tools
where dsquery >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] dsquery.exe not found. Install RSAT tools.
pause
exit /b 1
)
echo [PROCESS] Auditing contact metadata for "%TARGET%"...
:: Capture email, skipping header and filtering footer
set "USER_EMAIL="
for /f "skip=1 tokens=*" %%a in ('dsquery user -samid "%TARGET%" ^| dsget user -email 2^>nul') do (
for /f "tokens=*" %%b in ("%%a") do (
echo %%b | findstr /i /c:"dsget succeeded" >nul
if errorlevel 1 if not "%%b"=="" set "USER_EMAIL=%%b"
)
)
if defined USER_EMAIL (
echo [SUCCESS] Email: %USER_EMAIL%
) else (
echo [INFO] No email address is set for "%TARGET%".
echo [TIP] Set one with: dsmod user [DN] -email "user@company.com"
)
pause
Creating a Contact Info Diagnostic Tool
This professional script takes a username and provides a comprehensive contact summary with email, display name, and department.
@echo off
setlocal EnableDelayedExpansion
echo ============================================================
echo Active Directory Contact Lookup Tool
echo ============================================================
set /p "USN=Enter Username: "
if "!USN!"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)
:: Check if AD PowerShell module is available
powershell -NoProfile -Command "if (-not (Get-Module -ListAvailable ActiveDirectory)) { exit 1 }" 2>nul
if !errorlevel! neq 0 (
echo [ERROR] Active Directory PowerShell module not available.
echo [HELP] Install RSAT: Settings ^> Apps ^> Optional Features ^> Add RSAT
pause
exit /b 1
)
echo.
echo [PROCESS] Querying Active Directory for "!USN!"...
echo.
powershell -NoProfile -Command ^
"try {" ^
" $user = Get-ADUser -Identity '!USN!' -Properties EmailAddress, DisplayName, Department, Title, OfficePhone;" ^
" Write-Host ' Display Name: ' $(if ($user.DisplayName) { $user.DisplayName } else { '(not set)' });" ^
" Write-Host ' Email: ' $(if ($user.EmailAddress) { $user.EmailAddress } else { '(not set)' });" ^
" Write-Host ' Department: ' $(if ($user.Department) { $user.Department } else { '(not set)' });" ^
" Write-Host ' Title: ' $(if ($user.Title) { $user.Title } else { '(not set)' });" ^
" Write-Host ' Phone: ' $(if ($user.OfficePhone) { $user.OfficePhone } else { '(not set)' })" ^
"} catch {" ^
" Write-Host '[ERROR] User ''!USN!'' not found in Active Directory.';" ^
" exit 1" ^
"}" 2>nul
echo.
echo ============================================================
pause
Common Pitfalls and How to Avoid Them
Blank Email Fields
Note that "Email" is an optional field in AD. If it wasn't filled out when the account was created, dsget will return a blank line.
Solution:
Always include an if not defined check in your script to handle empty metadata gracefully.
Multi-Email Complexity
Active Directory can store multiple email addresses (Aliases) in the proxyAddresses attribute. The dsget -email and Get-ADUser -Properties EmailAddress only show the Primary/Default SMTP address.
Advise your users that if they need to see all of a person's aliases, they must use the PowerShell bridge to query the proxyAddresses property: Get-ADUser <USN> -Properties proxyAddresses.
Best Practices for Contact Management
- Validate on Onboarding: Use your script as part of the new-user setup to ensure that the email address follows the company format (e.g.,
firstname.lastname@company.com). - Audit Distribution Groups: If a user is a member of a "Managers" group, run your script to ensure their email is active so they receive departmental announcements.
- Use for Logging: When a script logs an error, have it automatically look up the administrator's email so the alert can be routed correctly.
Inside raw LDAP queries or advanced programming, the "Email" attribute is historically called mail.
Conclusion
Getting a user's email address from Active Directory via Batch script is a critical skill for any IT administrator focused on communication and automation. By leveraging the dsquery and dsget utilities to programmatically extract contact data, you can build responsive systems that keep users informed and ensure your directory is always a reliable source of truth. This professional approach to system identification maintains a clear and accessible channel between IT and the user base, providing a solid foundation for your communication strategy across the entire Windows network.