Introduction: What is Active Directory and Why It Matters
Active Directory (AD) is Microsoft’s directory service for Windows domain networks. It stores information about objects on the network and makes this information available to users and administrators. AD provides centralized authentication, authorization, and management of resources, making it the backbone of enterprise Windows environments. Mastering AD commands is essential for efficient network administration, security management, and troubleshooting.
Core Concepts and Components
- Domain: A logical group of network objects (users, devices, groups) that share the same AD database
- Domain Controller (DC): Server that runs AD Domain Services and stores the AD database
- Forest: Collection of one or more domains that share a common schema and global catalog
- Organizational Unit (OU): Container for organizing objects within a domain
- Group Policy: Feature for implementing specific configurations for users and computers
- LDAP (Lightweight Directory Access Protocol): Protocol used to communicate with AD
- Global Catalog (GC): Contains a partial copy of all objects in a multi-domain forest
Command Environments
Active Directory can be managed through multiple command-line interfaces:
- PowerShell with Active Directory module (modern, preferred method)
- dsquery, dsmod, dsadd and other command-line tools
- ADSI (Active Directory Service Interfaces)
- ldp.exe and other LDAP tools
- ntdsutil for advanced directory operations
PowerShell Active Directory Commands
Module Import and Authentication
# Import AD Module (required for most AD PowerShell commands)
Import-Module ActiveDirectory
# Connect to a specific domain (optional)
Set-ADDomainController -Identity "DC01.domain.com"
# Connect to AD with alternate credentials
$credential = Get-Credential
New-PSDrive -Name ADDrive -PSProvider ActiveDirectory -Root "//RootDSE/" -Credential $credential
User Management Commands
Operation | PowerShell Command | Description |
---|
Create User | New-ADUser -Name "John Smith" -GivenName "John" -Surname "Smith" -SamAccountName "jsmith" -UserPrincipalName "jsmith@domain.com" -Path "OU=Users,DC=domain,DC=com" -AccountPassword (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) -Enabled $true | Creates a new Active Directory user |
Get User | Get-ADUser -Identity "jsmith" -Properties * | Retrieves user details with all properties |
Find Users | Get-ADUser -Filter 'Department -eq "IT"' -SearchBase "OU=Users,DC=domain,DC=com" | Finds users matching specific criteria |
Modify User | Set-ADUser -Identity "jsmith" -Title "System Administrator" -Department "IT" | Updates user properties |
Reset Password | Set-ADAccountPassword -Identity "jsmith" -Reset -NewPassword (ConvertTo-SecureString "NewP@ssw0rd" -AsPlainText -Force) | Resets a user’s password |
Enable/Disable User | Enable-ADAccount -Identity "jsmith" <br> Disable-ADAccount -Identity "jsmith" | Enables or disables a user account |
Unlock Account | Unlock-ADAccount -Identity "jsmith" | Unlocks a locked user account |
Delete User | Remove-ADUser -Identity "jsmith" -Confirm:$false | Deletes a user account |
Move User | Move-ADObject -Identity "CN=John Smith,OU=OldOU,DC=domain,DC=com" -TargetPath "OU=NewOU,DC=domain,DC=com" | Moves a user to a different OU |
Group Management Commands
Operation | PowerShell Command | Description |
---|
Create Group | New-ADGroup -Name "IT Support" -SamAccountName "IT_Support" -GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=domain,DC=com" | Creates a new security group |
Get Group | Get-ADGroup -Identity "IT_Support" -Properties * | Retrieves group details |
Find Groups | Get-ADGroup -Filter 'Name -like "*IT*"' -SearchBase "OU=Groups,DC=domain,DC=com" | Finds groups by name pattern |
Add Member | Add-ADGroupMember -Identity "IT_Support" -Members "jsmith" | Adds a user to a group |
Remove Member | Remove-ADGroupMember -Identity "IT_Support" -Members "jsmith" -Confirm:$false | Removes a user from a group |
Get Group Members | Get-ADGroupMember -Identity "IT_Support" | Lists all members of a group |
Get User Groups | Get-ADPrincipalGroupMembership -Identity "jsmith" | Lists all groups a user is a member of |
Delete Group | Remove-ADGroup -Identity "IT_Support" -Confirm:$false | Deletes a group |
Computer Management Commands
Operation | PowerShell Command | Description |
---|
Create Computer | New-ADComputer -Name "WS01" -SamAccountName "WS01" -Path "OU=Workstations,DC=domain,DC=com" | Creates a new computer account |
Get Computer | Get-ADComputer -Identity "WS01" -Properties * | Retrieves computer details |
Find Computers | Get-ADComputer -Filter 'OperatingSystem -like "*Windows 10*"' -Properties OperatingSystem | Finds computers by OS |
Move Computer | Move-ADObject -Identity "CN=WS01,OU=OldOU,DC=domain,DC=com" -TargetPath "OU=NewOU,DC=domain,DC=com" | Moves a computer to a different OU |
Delete Computer | Remove-ADComputer -Identity "WS01" -Confirm:$false | Deletes a computer account |
Reset Computer | Reset-ComputerMachinePassword -Server "DC01.domain.com" -Credential (Get-Credential) | Resets computer account password |
Organizational Unit (OU) Management
Operation | PowerShell Command | Description |
---|
Create OU | New-ADOrganizationalUnit -Name "Finance" -Path "DC=domain,DC=com" -ProtectedFromAccidentalDeletion $true | Creates a new OU |
Get OU | Get-ADOrganizationalUnit -Identity "OU=Finance,DC=domain,DC=com" -Properties * | Retrieves OU details |
Find OUs | Get-ADOrganizationalUnit -Filter 'Name -like "*Dept*"' -SearchBase "DC=domain,DC=com" | Finds OUs by name pattern |
Delete OU | Set-ADOrganizationalUnit -Identity "OU=Finance,DC=domain,DC=com" -ProtectedFromAccidentalDeletion $false <br> Remove-ADOrganizationalUnit -Identity "OU=Finance,DC=domain,DC=com" -Confirm:$false | Deletes an OU (must first disable protection) |
Domain Controller Management
Operation | PowerShell Command | Description |
---|
Get Domain Controllers | Get-ADDomainController -Filter * | Lists all domain controllers |
Get FSMO Roles | `Get-ADDomain | Select-Object InfrastructureMaster, RIDMaster, PDCEmulator<br> Get-ADForest |
Force Replication | Sync-ADObject -Object "CN=John Smith,OU=Users,DC=domain,DC=com" -Source "DC01.domain.com" -Destination "DC02.domain.com" | Forces replication of an object |
Test Replication | Test-ReplicationHealth | Tests AD replication health (run on DC) |
Get Domain Info | Get-ADDomain | Shows domain information |
Get Forest Info | Get-ADForest | Shows forest information |
Group Policy Management
Operation | PowerShell Command | Description |
---|
Get GPOs | Get-GPO -All | Lists all Group Policy Objects |
Get Specific GPO | Get-GPO -Name "Default Domain Policy" | Gets a specific GPO |
Create GPO | New-GPO -Name "Security Settings" | Creates a new GPO |
Link GPO | New-GPLink -Name "Security Settings" -Target "OU=Users,DC=domain,DC=com" -LinkEnabled Yes | Links a GPO to an OU |
Remove GPO Link | Remove-GPLink -Name "Security Settings" -Target "OU=Users,DC=domain,DC=com" | Removes a GPO link |
Set GPO Status | Set-GPLink -Name "Security Settings" -Target "OU=Users,DC=domain,DC=com" -LinkEnabled No | Enables/disables a GPO link |
Delete GPO | Remove-GPO -Name "Security Settings" | Deletes a GPO |
Backup GPO | Backup-GPO -Name "Security Settings" -Path "C:\GPOBackups" | Backs up a GPO |
Restore GPO | Restore-GPO -Name "Security Settings" -Path "C:\GPOBackups" | Restores a GPO from backup |
Classic Command-Line Tools (dsquery, dsmod, dsadd)
DSQuery Commands
Operation | Command | Description |
---|
Find Users | dsquery user -name "John*" | Finds users by name pattern |
Find Computers | dsquery computer -name "WS*" | Finds computers by name pattern |
Find Groups | dsquery group -name "IT*" | Finds groups by name pattern |
Find OUs | dsquery ou -name "Finance" | Finds OUs by name |
Find Disabled Accounts | dsquery user -disabled | Finds disabled user accounts |
Find Locked Accounts | `dsquery user -disabled -limit 0 | dsget user -samid -acctexpires -disabled -pwdexpires -lastlogon -lastlogontst` |
DSAdd Commands
Operation | Command | Description |
---|
Add User | dsadd user "CN=John Smith,OU=Users,DC=domain,DC=com" -samid jsmith -upn jsmith@domain.com -fn John -ln Smith -pwd P@ssw0rd -mustchpwd yes | Creates a new user |
Add Group | dsadd group "CN=IT Support,OU=Groups,DC=domain,DC=com" -secgrp yes -scope g | Creates a new security group |
Add Computer | dsadd computer "CN=WS01,OU=Computers,DC=domain,DC=com" | Creates a new computer account |
Add OU | dsadd ou "OU=Finance,DC=domain,DC=com" | Creates a new OU |
DSMod Commands
Operation | Command | Description |
---|
Modify User | dsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -title "Manager" -dept "Finance" | Updates user properties |
Reset Password | dsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -pwd NewP@ssw0rd -mustchpwd yes | Resets a user’s password |
Disable User | dsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -disabled yes | Disables a user account |
Enable User | dsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -disabled no | Enables a user account |
Modify Group | dsmod group "CN=IT Support,OU=Groups,DC=domain,DC=com" -secgrp yes -scope g | Updates group properties |
DSRm Commands
Operation | Command | Description |
---|
Delete User | dsrm "CN=John Smith,OU=Users,DC=domain,DC=com" -subtree | Deletes a user |
Delete Group | dsrm "CN=IT Support,OU=Groups,DC=domain,DC=com" -subtree | Deletes a group |
Delete Computer | dsrm "CN=WS01,OU=Computers,DC=domain,DC=com" -subtree | Deletes a computer |
Delete OU | dsrm "OU=Finance,DC=domain,DC=com" -subtree | Deletes an OU and its contents |
LDAP Query Syntax
LDAP filters are used in many AD commands to specify search criteria.
Common LDAP Filters
Target | LDAP Filter | Description |
---|
All Users | (objectClass=user)(objectCategory=person) | Finds all user objects |
Disabled Users | (&(objectClass=user)(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=2)) | Finds disabled user accounts |
Enabled Users | (&(objectClass=user)(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2))) | Finds enabled user accounts |
Locked Users | (&(objectClass=user)(objectCategory=person)(lockoutTime>=1)) | Finds locked user accounts |
Password Never Expires | (&(objectClass=user)(objectCategory=person)(userAccountControl:1.2.840.113556.1.4.803:=65536)) | Finds accounts with non-expiring passwords |
Password Expired | (&(objectClass=user)(objectCategory=person)(pwdLastSet=0)) | Finds accounts with expired passwords |
All Computers | (objectClass=computer) | Finds all computer objects |
All Groups | (objectClass=group) | Finds all group objects |
Security Groups | (&(objectClass=group)(groupType:1.2.840.113556.1.4.803:=2147483648)) | Finds security groups |
Distribution Groups | (&(objectClass=group)(!(groupType:1.2.840.113556.1.4.803:=2147483648))) | Finds distribution groups |
Domain Controllers | (&(objectClass=computer)(userAccountControl:1.2.840.113556.1.4.803:=8192)) | Finds domain controllers |
Using LDAP Filters in PowerShell
# Find disabled users
Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=2))"
# Find computers running Windows 10
Get-ADComputer -LDAPFilter "(&(objectClass=computer)(operatingSystem=*Windows 10*))"
# Find members of a specific group using LDAP
Get-ADUser -LDAPFilter "(&(objectCategory=person)(objectClass=user)(memberOf=CN=IT Support,OU=Groups,DC=domain,DC=com))"
Advanced Domain Operations with ntdsutil
ntdsutil is a command-line tool used for AD database maintenance.
# Launch ntdsutil
ntdsutil
# Activate instance NTDS
ntdsutil: activate instance ntds
# Launch authoritative restore
ntdsutil: authoritative restore
# Perform FSMO role transfer
ntdsutil: roles
fsmo maintenance: connections
server connections: connect to server dc01.domain.com
server connections: quit
fsmo maintenance: transfer pdc
fsmo maintenance: quit
ntdsutil: quit
# Perform AD database maintenance
ntdsutil: activate instance ntds
ntdsutil: files
file maintenance: compact to c:\temp
file maintenance: quit
ntdsutil: quit
# Reset Directory Service Restore Mode (DSRM) password
ntdsutil: set dsrm password
reset password on server null: reset password
Please type password for DS Restore Mode Administrator Account: ********
Please confirm new password: ********
ntdsutil: quit
Common Challenges and Solutions
Challenge | Solution |
---|
AD Replication Issues | repadmin /replsummary – Check replication summary <br> repadmin /showrepl – Show replication status <br> repadmin /syncall /Aed – Force enterprise-wide replication |
DNS Problems | dcdiag /test:dns – Run DNS diagnostics <br> netdiag /test:dns – Test DNS client configuration <br> ipconfig /flushdns – Clear DNS cache |
Trust Relationship Failed | Test-ComputerSecureChannel -Repair – Repair computer trust relationship <br> Or rejoin computer to domain |
GPO Not Applying | gpupdate /force – Force Group Policy update <br> gpresult /r – Show resultant set of policy <br> gpresult /h c:\gpresult.html – Detailed GPO report |
Account Lockout Troubleshooting | Search-ADAccount -LockedOut – Find locked accounts <br> eventcr.msc – Check security logs on domain controller |
Best Practices and Tips
PowerShell One-Liners: Create reusable one-liner scripts for common tasks
# Create a CSV report of disabled user accounts
Get-ADUser -Filter {Enabled -eq $false} -Properties Name,LastLogonDate,Description | Select Name,LastLogonDate,Description | Export-CSV "C:\DisabledUsers.csv" -NoTypeInformation
# Find inactive computers (not logged in for 90 days)
$date = (Get-Date).AddDays(-90)
Get-ADComputer -Filter {LastLogonDate -lt $date} -Properties LastLogonDate | Select Name,LastLogonDate
# Clean up inactive user accounts
Get-ADUser -Filter {LastLogonDate -lt $date -and Enabled -eq $true} -Properties LastLogonDate | Disable-ADAccount
Use PowerShell for Bulk Operations:
# Import users from CSV
Import-Csv "C:\Users.csv" | ForEach-Object {
New-ADUser -Name $_.Name -GivenName $_.FirstName -Surname $_.LastName -SamAccountName $_.Username -Path $_.OU -AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force) -Enabled $true
}
# Export all users to CSV
Get-ADUser -Filter * -Properties * | Select-Object Name,GivenName,Surname,SamAccountName,EmailAddress,Department,Title,LastLogonDate | Export-Csv "C:\AllUsers.csv" -NoTypeInformation
Security Best Practices:
- Use fine-grained password policies for different user groups
- Implement least privilege access model
- Regularly audit AD using built-in or third-party tools
- Use tiered administration model for AD management
- Enable and monitor AD auditing
Maintenance Tips:
- Schedule regular backups of AD (System State backup)
- Clean up orphaned or inactive accounts
- Monitor AD replication health
- Document your AD structure and changes
PowerShell Reporting Examples
# Password expiration report
Get-ADUser -Filter * -Properties PasswordLastSet,PasswordNeverExpires,PasswordExpired |
Select-Object Name,SamAccountName,PasswordLastSet,PasswordNeverExpires,PasswordExpired |
Export-CSV "C:\PasswordReport.csv" -NoTypeInformation
# Group membership report
$groups = Get-ADGroup -Filter *
$report = foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group.DistinguishedName | Select-Object -ExpandProperty Name
[PSCustomObject]@{
GroupName = $group.Name
Members = ($members -join ", ")
MemberCount = $members.Count
}
}
$report | Export-CSV "C:\GroupMembership.csv" -NoTypeInformation
# AD health check
$report = @()
$dcs = Get-ADDomainController -Filter *
foreach ($dc in $dcs) {
$dcName = $dc.HostName
# Test LDAP
$ldapTest = Test-NetConnection -ComputerName $dcName -Port 389 -InformationLevel Quiet
# Test RPC
$rpcTest = Test-NetConnection -ComputerName $dcName -Port 135 -InformationLevel Quiet
# Test PING
$pingTest = Test-Connection -ComputerName $dcName -Count 1 -Quiet
# Get uptime
try {
$os = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $dcName -ErrorAction SilentlyContinue
$uptime = (Get-Date) - $os.ConvertToDateTime($os.LastBootUpTime)
$uptimeStr = "$($uptime.Days) days, $($uptime.Hours) hours, $($uptime.Minutes) minutes"
} catch {
$uptimeStr = "Unable to retrieve"
}
$report += [PSCustomObject]@{
DomainController = $dcName
LDAP = if ($ldapTest) {"Available"} else {"Unavailable"}
RPC = if ($rpcTest) {"Available"} else {"Unavailable"}
Ping = if ($pingTest) {"Available"} else {"Unavailable"}
Uptime = $uptimeStr
}
}
$report | Export-CSV "C:\DCHealthCheck.csv" -NoTypeInformation
Resources for Further Learning
Official Documentation
Books
- “Active Directory: Designing, Deploying, and Running Active Directory” by Brian Desmond
- “Windows Server 2019 & PowerShell All-in-One For Dummies” by Sara Perrott
- “Learn Windows PowerShell in a Month of Lunches” by Don Jones and Jeffrey Hicks
Online Resources
Tools