Essential Active Directory Commands Cheat Sheet: PowerShell and CMD Reference

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:

  1. PowerShell with Active Directory module (modern, preferred method)
  2. dsquery, dsmod, dsadd and other command-line tools
  3. ADSI (Active Directory Service Interfaces)
  4. ldp.exe and other LDAP tools
  5. 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

OperationPowerShell CommandDescription
Create UserNew-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 $trueCreates a new Active Directory user
Get UserGet-ADUser -Identity "jsmith" -Properties *Retrieves user details with all properties
Find UsersGet-ADUser -Filter 'Department -eq "IT"' -SearchBase "OU=Users,DC=domain,DC=com"Finds users matching specific criteria
Modify UserSet-ADUser -Identity "jsmith" -Title "System Administrator" -Department "IT"Updates user properties
Reset PasswordSet-ADAccountPassword -Identity "jsmith" -Reset -NewPassword (ConvertTo-SecureString "NewP@ssw0rd" -AsPlainText -Force)Resets a user’s password
Enable/Disable UserEnable-ADAccount -Identity "jsmith" <br> Disable-ADAccount -Identity "jsmith"Enables or disables a user account
Unlock AccountUnlock-ADAccount -Identity "jsmith"Unlocks a locked user account
Delete UserRemove-ADUser -Identity "jsmith" -Confirm:$falseDeletes a user account
Move UserMove-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

OperationPowerShell CommandDescription
Create GroupNew-ADGroup -Name "IT Support" -SamAccountName "IT_Support" -GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=domain,DC=com"Creates a new security group
Get GroupGet-ADGroup -Identity "IT_Support" -Properties *Retrieves group details
Find GroupsGet-ADGroup -Filter 'Name -like "*IT*"' -SearchBase "OU=Groups,DC=domain,DC=com"Finds groups by name pattern
Add MemberAdd-ADGroupMember -Identity "IT_Support" -Members "jsmith"Adds a user to a group
Remove MemberRemove-ADGroupMember -Identity "IT_Support" -Members "jsmith" -Confirm:$falseRemoves a user from a group
Get Group MembersGet-ADGroupMember -Identity "IT_Support"Lists all members of a group
Get User GroupsGet-ADPrincipalGroupMembership -Identity "jsmith"Lists all groups a user is a member of
Delete GroupRemove-ADGroup -Identity "IT_Support" -Confirm:$falseDeletes a group

Computer Management Commands

OperationPowerShell CommandDescription
Create ComputerNew-ADComputer -Name "WS01" -SamAccountName "WS01" -Path "OU=Workstations,DC=domain,DC=com"Creates a new computer account
Get ComputerGet-ADComputer -Identity "WS01" -Properties *Retrieves computer details
Find ComputersGet-ADComputer -Filter 'OperatingSystem -like "*Windows 10*"' -Properties OperatingSystemFinds computers by OS
Move ComputerMove-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 ComputerRemove-ADComputer -Identity "WS01" -Confirm:$falseDeletes a computer account
Reset ComputerReset-ComputerMachinePassword -Server "DC01.domain.com" -Credential (Get-Credential)Resets computer account password

Organizational Unit (OU) Management

OperationPowerShell CommandDescription
Create OUNew-ADOrganizationalUnit -Name "Finance" -Path "DC=domain,DC=com" -ProtectedFromAccidentalDeletion $trueCreates a new OU
Get OUGet-ADOrganizationalUnit -Identity "OU=Finance,DC=domain,DC=com" -Properties *Retrieves OU details
Find OUsGet-ADOrganizationalUnit -Filter 'Name -like "*Dept*"' -SearchBase "DC=domain,DC=com"Finds OUs by name pattern
Delete OUSet-ADOrganizationalUnit -Identity "OU=Finance,DC=domain,DC=com" -ProtectedFromAccidentalDeletion $false <br> Remove-ADOrganizationalUnit -Identity "OU=Finance,DC=domain,DC=com" -Confirm:$falseDeletes an OU (must first disable protection)

Domain Controller Management

OperationPowerShell CommandDescription
Get Domain ControllersGet-ADDomainController -Filter *Lists all domain controllers
Get FSMO Roles`Get-ADDomainSelect-Object InfrastructureMaster, RIDMaster, PDCEmulator<br>Get-ADForest
Force ReplicationSync-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 ReplicationTest-ReplicationHealthTests AD replication health (run on DC)
Get Domain InfoGet-ADDomainShows domain information
Get Forest InfoGet-ADForestShows forest information

Group Policy Management

OperationPowerShell CommandDescription
Get GPOsGet-GPO -AllLists all Group Policy Objects
Get Specific GPOGet-GPO -Name "Default Domain Policy"Gets a specific GPO
Create GPONew-GPO -Name "Security Settings"Creates a new GPO
Link GPONew-GPLink -Name "Security Settings" -Target "OU=Users,DC=domain,DC=com" -LinkEnabled YesLinks a GPO to an OU
Remove GPO LinkRemove-GPLink -Name "Security Settings" -Target "OU=Users,DC=domain,DC=com"Removes a GPO link
Set GPO StatusSet-GPLink -Name "Security Settings" -Target "OU=Users,DC=domain,DC=com" -LinkEnabled NoEnables/disables a GPO link
Delete GPORemove-GPO -Name "Security Settings"Deletes a GPO
Backup GPOBackup-GPO -Name "Security Settings" -Path "C:\GPOBackups"Backs up a GPO
Restore GPORestore-GPO -Name "Security Settings" -Path "C:\GPOBackups"Restores a GPO from backup

Classic Command-Line Tools (dsquery, dsmod, dsadd)

DSQuery Commands

OperationCommandDescription
Find Usersdsquery user -name "John*"Finds users by name pattern
Find Computersdsquery computer -name "WS*"Finds computers by name pattern
Find Groupsdsquery group -name "IT*"Finds groups by name pattern
Find OUsdsquery ou -name "Finance"Finds OUs by name
Find Disabled Accountsdsquery user -disabledFinds disabled user accounts
Find Locked Accounts`dsquery user -disabled -limit 0dsget user -samid -acctexpires -disabled -pwdexpires -lastlogon -lastlogontst`

DSAdd Commands

OperationCommandDescription
Add Userdsadd user "CN=John Smith,OU=Users,DC=domain,DC=com" -samid jsmith -upn jsmith@domain.com -fn John -ln Smith -pwd P@ssw0rd -mustchpwd yesCreates a new user
Add Groupdsadd group "CN=IT Support,OU=Groups,DC=domain,DC=com" -secgrp yes -scope gCreates a new security group
Add Computerdsadd computer "CN=WS01,OU=Computers,DC=domain,DC=com"Creates a new computer account
Add OUdsadd ou "OU=Finance,DC=domain,DC=com"Creates a new OU

DSMod Commands

OperationCommandDescription
Modify Userdsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -title "Manager" -dept "Finance"Updates user properties
Reset Passworddsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -pwd NewP@ssw0rd -mustchpwd yesResets a user’s password
Disable Userdsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -disabled yesDisables a user account
Enable Userdsmod user "CN=John Smith,OU=Users,DC=domain,DC=com" -disabled noEnables a user account
Modify Groupdsmod group "CN=IT Support,OU=Groups,DC=domain,DC=com" -secgrp yes -scope gUpdates group properties

DSRm Commands

OperationCommandDescription
Delete Userdsrm "CN=John Smith,OU=Users,DC=domain,DC=com" -subtreeDeletes a user
Delete Groupdsrm "CN=IT Support,OU=Groups,DC=domain,DC=com" -subtreeDeletes a group
Delete Computerdsrm "CN=WS01,OU=Computers,DC=domain,DC=com" -subtreeDeletes a computer
Delete OUdsrm "OU=Finance,DC=domain,DC=com" -subtreeDeletes an OU and its contents

LDAP Query Syntax

LDAP filters are used in many AD commands to specify search criteria.

Common LDAP Filters

TargetLDAP FilterDescription
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

ChallengeSolution
AD Replication Issuesrepadmin /replsummary – Check replication summary <br> repadmin /showrepl – Show replication status <br> repadmin /syncall /Aed – Force enterprise-wide replication
DNS Problemsdcdiag /test:dns – Run DNS diagnostics <br> netdiag /test:dns – Test DNS client configuration <br> ipconfig /flushdns – Clear DNS cache
Trust Relationship FailedTest-ComputerSecureChannel -Repair – Repair computer trust relationship <br> Or rejoin computer to domain
GPO Not Applyinggpupdate /force – Force Group Policy update <br> gpresult /r – Show resultant set of policy <br> gpresult /h c:\gpresult.html – Detailed GPO report
Account Lockout TroubleshootingSearch-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

Scroll to Top