Skip to main content

How to Get Detailed Active Directory User Attributes in Batch Script

Active Directory (AD) stores a wealth of information about every user in an organization, far beyond just their username and password. This includes their email address, department, job title, manager, and phone number. For IT administrators, being able to "Fetch" these detailed attributes via a Batch script is essential for generating staff directories, automating onboarding, or auditing security groups.

This guide explains how to use the legacy dsget tool and the modern PowerShell bridge to extract AD user details.

Why Fetch AD Attributes via Script?

  • Employee Directory Generation: Automatically creating a text or CSV file containing contact info for everyone in a specific department.
  • Onboarding Automation: Verifying that a new user has all their mandatory fields (like "Department" or "Work Phone") filled out correctly.
  • Security Auditing: Extracting the "Last Password Set" or "Account Expiration" date for every user in a privileged group.
Tool Availability

To use the dsquery and dsget commands, you must have the Remote Server Administration Tools (RSAT) installed on your workstation.

Method 1: Using DSGET (The Classic Way)

The dsget utility is designed to work with "Distinguished Names" (DNs) provided by dsquery.

@echo off
setlocal

set "USER_NAME=John Doe"

:: Verify RSAT tools are available
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
)

echo [PROCESS] Searching for attributes for: "%USER_NAME%"...
echo.

:: 1. We find the user and pipe their identity to dsget
:: 2. We request specific fields: displayName, Email, Department
dsquery user -name "%USER_NAME%" | dsget user -display -email -dept

if %errorlevel% neq 0 (
echo [ERROR] User not found or Domain Controller is unreachable.
echo [HELP] Ensure you are connected to the domain network.
)
pause

Method 2: Using the PowerShell Bridge (The Modern Standard)

Modern AD administration is best handled via the Get-ADUser cmdlet. You can call this directly from Batch to get much more granular data.

@echo off
setlocal

set "USN=jdoe"

echo [PROCESS] Pulling extended metadata from Active Directory...
echo.

powershell -NoProfile -Command ^
"try {" ^
" Get-ADUser -Identity '%USN%' -Properties EmailAddress, Title, Department |" ^
" Select-Object Name, EmailAddress, Title, Department |" ^
" Format-List" ^
"} catch {" ^
" Write-Host '[ERROR] User ''%USN%'' not found or AD module not available.';" ^
" Write-Host '[HELP] Install RSAT: Settings > Apps > Optional Features > Add RSAT';" ^
" exit 1" ^
"}" 2>nul

pause

Creating a Staff Lookup Utility

This professional script validates input, checks for tool availability, and returns a formatted display of AD data.

@echo off
setlocal EnableDelayedExpansion

echo ============================================================
echo Active Directory Identity Prober
echo ============================================================

set /p "TARGET=Enter Username (SAMAccountName): "

if "!TARGET!"=="" (
echo [ERROR] No username entered.
pause
exit /b 1
)

:: Check if the 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 is not installed.
echo [HELP] Install RSAT: Settings ^> Apps ^> Optional Features ^> Add RSAT
pause
exit /b 1
)

echo.
echo [PROCESS] Fetching data for "!TARGET!"...
echo.

powershell -NoProfile -Command ^
"try {" ^
" $user = Get-ADUser -Identity '!TARGET!' -Properties EmailAddress, Title, Department, Manager, OfficePhone, PasswordLastSet, AccountExpirationDate;" ^
" $mgr = if ($user.Manager) { (Get-ADUser $user.Manager).Name } else { '(not set)' };" ^
" Write-Host ' Name: ' $user.Name;" ^
" Write-Host ' Job Title: ' $(if ($user.Title) { $user.Title } 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 ' Phone: ' $(if ($user.OfficePhone) { $user.OfficePhone } else { '(not set)' });" ^
" Write-Host ' Manager: ' $mgr;" ^
" Write-Host ' Password Set:' $user.PasswordLastSet;" ^
" Write-Host ' Acct Expires:' $(if ($user.AccountExpirationDate) { $user.AccountExpirationDate } else { 'Never' })" ^
"} catch {" ^
" Write-Host '[ERROR] User ''!TARGET!'' not found in Active Directory.';" ^
" Write-Host '[TIP] Verify the SAMAccountName is correct.';" ^
" exit 1" ^
"}" 2>nul

echo.
echo ============================================================
pause

Common Pitfalls and How to Avoid Them

Domain Connectivity

Your computer must be joined to the domain and have a clear line of sight to a Domain Controller (DC). If you are working from home, ensure your VPN is active.

Attribute Naming (LDAP vs PowerShell)

Note that attribute names are slightly different depending on the tool you use.

Wrong Way:

dsget user -EmailAddress
:: Result: "dsget failed: Unknown option -EmailAddress"

Correct Way:

  • In dsget, the email field is called -email.
  • In PowerShell, the same field is called EmailAddress.
  • In the raw AD database (LDAP), it is called mail.
SEO and UX Tip

Advise your users that if they get "Access Denied," it is because their account doesn't have the "Read All User Information" permission in AD. Most standard office accounts can read these public fields, but "Account Expiration" or "Home Directory" might be restricted.

Best Practices for AD Data Management

  1. Use SAMAccountName: When searching for users, always prefer the SAMAccountName (e.g., jdoe) over the "Display Name," as display names are not unique.
  2. Handle Multi-Value Fields: Some fields (like proxyAddresses) can contain multiple items. You must use PowerShell's -join operator to display them cleanly in a text report.
  3. Export to CSV: If you are auditing an entire department, use the command: powershell -NoProfile -Command "Get-ADUser -Filter {Department -eq 'Engineering'} -Properties * | Export-CSV report.csv -NoTypeInformation".
PII Data

Always be mindful of Personally Identifiable Information (PII). If your script handles home addresses or personal phone numbers, ensure the resulting files are stored on a secure, encrypted drive.

Conclusion

Querying detailed Active Directory user attributes via Batch script is a core competency for any professional Windows administrator. By moving beyond simple usernames and utilizing tools like dsget and PowerShell to extract rich metadata, you can automate identity management, simplify reporting, and improve the overall efficiency of your help desk operations. This professional approach to system identification ensures that your organization's directory data is always accurate and accessible, providing a stable foundation for your enterprise-level automation across the entire Windows network.