HomeNewsletterCommunityToolsArchiveBlogToday's NewsAboutQuick Links Subscribe free
← Back to Blog
Active Directory Active DirectoryPowerShellWindows ServerAD HealthFSMOReplicationDomain Controllers

10 Essential PowerShell Commands Every Active Directory Administrator Should Know

IA
Imran Awan
12 July 2026

Active Directory sits at the heart of every enterprise environment. When it breaks — or when you suspect it might — you need to move fast. These 10 PowerShell commands cover the daily reality of AD administration: finding locked users, auditing groups, checking replication health, and reading the event logs that tell you exactly what went wrong and when.

Environment note: All commands below require the ActiveDirectory module. On a domain controller it is installed by default. On a member server or workstation, install RSAT: Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0. Run all commands from an elevated PowerShell session with Domain Admin rights unless stated otherwise.

1. Get-ADUser — Finding Users, Checking Account Status, Locked Accounts

Get-ADUser is the most-used command in any AD admin's toolkit. It queries the AD database via LDAP, returning user objects with the properties you request. Without -Properties * it returns only a default subset — you will miss LockedOut, PasswordExpired, and LastLogonDate unless you ask for them explicitly.

Windows PowerShell
Get-ADUser -Identity "jsmith" -Properties LockedOut,PasswordExpired,LastLogonDate,Enabled,PasswordLastSet Get-ADUser -Filter {LockedOut -eq $true} -Properties LockedOut,LastLogonDate | Select-Object Name,SamAccountName,LastLogonDate
# Output — locked accounts
Name SamAccountName LastLogonDate
---- -------------- -------------
John Smith jsmith 12/07/2026 08:14:22
Sarah Connor sconnor 11/07/2026 17:03:11

Under the hood: AD stores lockoutTime as a 64-bit Windows file time. When PowerShell returns LockedOut: True, it is reading that attribute against the domain's LockoutObservationWindow. LastLogonDate is replicated — LastLogon (non-replicated) is more accurate but only valid on the DC you queried.

Real-world scenario: Three people call the helpdesk on Monday morning saying they cannot log in. Run the filter above first — you will see all locked accounts in one shot, then pipe to Unlock-ADAccount.

Gotcha: LastLogonDate replicates every 9–14 days by default, not in real time. To find which DC a user last authenticated against, query LastLogon on every DC and take the maximum value.

2. Get-ADComputer — Querying Computer Objects, Finding Stale Devices

Stale computer objects are a security liability. They can have valid Kerberos tickets, open SMB shares, and group memberships granting access they should not have. Get-ADComputer lets you find and act on them before they become a problem.

Windows PowerShell
# Find computers not logged on in 90 days $cutoff = (Get-Date).AddDays(-90) Get-ADComputer -Filter {LastLogonDate -lt $cutoff -and Enabled -eq $true} -Properties LastLogonDate,OperatingSystem | Sort-Object LastLogonDate | Export-Csv "C:\Temp\StaleComputers.csv" -NoTypeInformation
# 47 stale objects found
Name OS LastLogonDate
---- -- -------------
LAPTOP-HR-022 Windows 10 Pro 14/04/2026 09:11:03
WS-FIN-007 Windows 11 Enterprise 02/05/2026 14:22:44

Under the hood: Get-ADComputer translates to an LDAP query against the domain. The filter converts to an LDAP filter string sent as an LDAP Search Request. Properties not in the default set require a second round-trip to retrieve.

Real-world scenario: Before a device lifecycle review, generate this CSV for the IT asset team. Disable objects first — move to a "Disabled" OU, wait 30 days for complaints, then delete.

Active Directory — Computer Objects Report
1,247
Total computers
47
Stale (>90 days)
1,188
Active (enabled)

3. Get-ADGroup / Get-ADGroupMember — Group Membership Auditing

Group membership sprawl is one of the most common causes of over-privileged accounts. Users accumulate memberships over years and nobody removes them. Get-ADGroupMember lets you audit who is in what, recursively.

Windows PowerShell
# All members of Domain Admins, including nested groups Get-ADGroupMember -Identity "Domain Admins" -Recursive | Select-Object Name,SamAccountName,ObjectClass | Sort-Object Name # Find all groups a specific user belongs to Get-ADUser -Identity "jsmith" -Properties MemberOf | Select-Object -ExpandProperty MemberOf
Name SamAccountName ObjectClass
---- -------------- -----------
Administrator Administrator user
John Smith jsmith user
SVC-Backup svc-backup user <-- service account in Domain Admins!
Watch out: Service accounts in Domain Admins is a critical finding. A compromised service account with Domain Admin rights means full domain takeover. Remove immediately and use minimum-privilege permissions. Log this in your ITSM system.

4. Search-ADAccount — Locked, Expired, and Disabled Accounts

Search-ADAccount is purpose-built for bulk account state queries. Where Get-ADUser -Filter requires knowing LDAP attributes, Search-ADAccount gives you readable switches that map to the correct underlying queries.

Windows PowerShell
# All locked accounts Search-ADAccount -LockedOut | Select-Object Name,SamAccountName,LockedOut # Accounts with expired passwords Search-ADAccount -PasswordExpired -UsersOnly | Select-Object Name,SamAccountName # Accounts inactive for 60+ days Search-ADAccount -AccountInactive -TimeSpan 60.00:00:00 -UsersOnly | Select-Object Name,LastLogonDate

Under the hood: -LockedOut queries the msDS-User-Account-Control-Computed bit flags. -AccountInactive uses lastLogonTimestamp which replicates every 9–14 days — not exact for very recent activity.

Real-world scenario: Before a major migration, run -AccountInactive with a 90-day timespan. Disable those accounts before cutover — they reduce your attack surface without being missed.

5. Get-ADDomain / Get-ADForest — Domain Health Information

These two commands give you the structural overview of your AD environment: who is the PDC emulator, what is the functional level, which DCs exist, and how forest trusts are wired. Run them when joining a new environment or diagnosing a forest-wide issue.

Windows PowerShell
Get-ADDomain | Select-Object DNSRoot,DomainMode,PDCEmulator,RIDMaster,InfrastructureMaster Get-ADForest | Select-Object Name,ForestMode,SchemaMaster,DomainNamingMaster,Domains,GlobalCatalogs
DNSRoot : corp.contoso.com
DomainMode : Windows2016Domain
PDCEmulator : DC01.corp.contoso.com
RIDMaster : DC01.corp.contoso.com
SchemaMaster : DC01.corp.contoso.com
GlobalCatalogs : {DC01.corp.contoso.com, DC02.corp.contoso.com}

Real-world scenario: A user reports their password reset is not propagating across offices. Check which DC is the PDC Emulator — it must be reachable from all branches for immediate password propagation. If it is down or unreachable from a site, that is your root cause.

Tip: Save a baseline right after building a domain: Get-ADDomain | Export-Clixml C:\AD-Baseline\domain-baseline.xml. Compare live state later with Compare-Object to spot configuration drift instantly.

6. Test-ComputerSecureChannel — DC Connectivity and Secure Channel Check

The secure channel is the authenticated connection between a workstation and a domain controller. When it breaks, the machine cannot authenticate users, apply Group Policy, or process Kerberos tickets. This command tests and can repair it without a domain rejoin.

Windows PowerShell — run on the affected workstation as Domain Admin
# Test only — returns True or False Test-ComputerSecureChannel -Verbose # Test and repair if broken Test-ComputerSecureChannel -Repair -Credential (Get-Credential)
# Broken channel:
VERBOSE: Performing the operation "Test-ComputerSecureChannel" on target "LAPTOP-HR-022".
False

# After -Repair:
True

Under the hood: The machine account password stored in HKLM\SECURITY\Policy\Secrets\$MACHINE.ACC must match what AD holds. After a VM snapshot restore they diverge — the channel breaks. -Repair calls NetrServerAuthenticate3 to reset the machine password in both places simultaneously.

Real-world scenario: A developer restores a VM from a 3-month-old snapshot. Group Policy stops applying, network shares fail. Run this — repair takes seconds, no rejoin required.

7. Get-ADDomainController — Listing DCs, Checking Roles and Site Assignments

When diagnosing AD issues you need a DC inventory — roles, site assignments, Global Catalog status. Get-ADDomainController gives you all of this in a single query.

Windows PowerShell
# List all DCs Get-ADDomainController -Filter "*" | Select-Object Name,Site,IPv4Address,IsGlobalCatalog,IsReadOnly,OperatingSystem | Format-Table -AutoSize # DCs with FSMO roles Get-ADDomainController -Filter "*" | Where-Object {$_.OperationMasterRoles} | Select-Object Name,OperationMasterRoles
Name Site IPv4Address IsGlobalCatalog IsReadOnly
---- ---- ----------- --------------- ----------
DC01 Default-First 10.0.0.10 True False
DC02 London-Site 10.10.0.10 True False
RODC1 Branch-Perth 192.168.5.10 True True
Active Directory Sites and Services — Domain Controllers
DC01.corp.contoso.comDefault-First-Site
GCPDC EmulatorRID Master
RODC1.corp.contoso.comBranch-Perth
GCRead-Only

8. Sync-ADObject / repadmin — Forcing Replication

When a change on one DC is not showing up on another, force replication rather than wait. Sync-ADObject replicates a single object immediately. repadmin /syncall triggers a full cycle across all DCs.

Windows PowerShell
# Replicate a single user to a specific DC $user = Get-ADUser -Identity "jsmith" Sync-ADObject -Object $user.DistinguishedName -Source DC01 -Destination DC02 # Force full replication across all DCs repadmin /syncall /AdeP # Check replication summary repadmin /replsummary
# replsummary — healthy output
Source DSA largest delta fails/total %%
DC01 00m:32s 0 / 14 0%
DC02 00m:44s 0 / 14 0%

Real-world scenario: A password was reset on DC01 but the user still cannot log in at the London office which authenticates against DC02. Sync-ADObject pushes that specific user immediately — no waiting for the scheduled replication interval.

Gotcha: repadmin /syncall /AdeP with /e triggers cross-site replication over WAN links immediately. Omit /e if you only need intra-site replication — avoid hammering a low-bandwidth branch link.

9. Get-ADReplicationFailure — Spotting Replication Errors Before They Become Disasters

Replication failures accumulate silently. By the time users notice problems, a DC may have been out of sync for hours or days. Get-ADReplicationFailure surfaces failures explicitly — error code, failing partner, and consecutive failure count.

Windows PowerShell
# Check replication failures across all DCs Get-ADReplicationFailure -Scope Domain | Select-Object Server,Partner,FirstFailureTime,FailureCount,LastError | Sort-Object FailureCount -Descending # Target a specific DC Get-ADReplicationFailure -Target DC02 -Scope Server
Server Partner FirstFailureTime FailureCount LastError
------ ------- ---------------- ------------ ---------
DC02 DC01 07/12/2026 06:14:22 47 8606 (Target principal name incorrect)
Error — Event ID 1311 — NTDS Replication
Computer: DC02.corp.contoso.com
Message: The KCC has detected problems with directory partition DC=corp,DC=contoso,DC=com. Insufficient site connectivity to create a spanning tree replication topology.
Error: 8606 — The target principal name is incorrect

Under the hood: Error 8606 typically means a Kerberos issue — the DC's machine account password is out of sync, or DNS is returning the wrong IP for the partner DC. Error 8453 means the replication account lacks permissions. Each error code maps to a specific root cause — always look them up rather than guessing.

Real-world scenario: After replacing a failed DC, set up replication then immediately run Get-ADReplicationFailure -Scope Domain. Catching errors at day 1 is far easier than diagnosing a split-brain AD database two weeks later.

10. Get-WinEvent — Reading AD Event Logs (4740 Lockout, 4625 Failed Logon)

The Security event log is the ground truth for what happened on a DC. Event ID 4740 tells you exactly which machine locked an account. Event ID 4625 shows every failed logon with the source workstation. Without these you are guessing at the cause of lockouts.

Windows PowerShell — run on the PDC Emulator
# Account lockout events — Event ID 4740 — last 24 hours Get-WinEvent -ComputerName DC01 -FilterHashtable @{ LogName = 'Security' Id = 4740 StartTime = (Get-Date).AddHours(-24) } | Select-Object TimeCreated, @{N='Account';E={$_.Properties[0].Value}}, @{N='CallerComputer';E={$_.Properties[1].Value}} # Failed logons — Event ID 4625 — grouped by account Get-WinEvent -ComputerName DC01 -FilterHashtable @{ LogName = 'Security' Id = 4625 StartTime = (Get-Date).AddHours(-1) } | Group-Object {$_.Properties[5].Value} | Sort-Object Count -Descending
# 4740 output
TimeCreated Account CallerComputer
----------- ------- --------------
12/07/2026 08:14:22 jsmith LAPTOP-HR-022
12/07/2026 08:14:23 jsmith LAPTOP-HR-022

# 4625 grouped
Count Name
----- ----
34 jsmith <-- 34 failures in 1 hour from one machine

Under the hood: Event ID 4740 is written on the PDC Emulator because all lockout processing flows there. The CallerComputer in Properties[1] is the machine that sent the failed authentication — this is how you trace whether it is an Outlook credential cache, a mapped drive, a scheduled task, or a phone with an old password.

Real-world scenario: jsmith is getting locked out repeatedly even after a password reset. The 4740 events show LAPTOP-HR-022 every time. You remote in and find a mapped drive in File Explorer using cached credentials from the old password. Clear it in Windows Credential Manager — lockouts stop immediately.

Watch out: The Security event log default maximum size is 20 MB — on a busy DC that covers less than an hour of authentication traffic. Increase to at least 512 MB via Group Policy: Computer Configuration › Windows Settings › Security Settings › Event Log › Maximum security log size. Forward events to a SIEM in real time so you never lose history.

Pipeline Combos — Three Commands to Save Right Now

The real power of PowerShell is composing these commands. Here are three pipelines that solve common AD problems in a single shot.

Combo 1 — Find and unlock all locked accounts

Windows PowerShell
Search-ADAccount -LockedOut -UsersOnly | Tee-Object -Variable locked | Select-Object Name,SamAccountName $locked | ForEach-Object { Unlock-ADAccount -Identity $_.SamAccountName; Write-Host "Unlocked: $($_.Name)" -ForegroundColor Green }

Combo 2 — Export all Domain Admins with last logon and enabled state

Windows PowerShell
Get-ADGroupMember -Identity "Domain Admins" -Recursive | Where-Object {$_.objectClass -eq "user"} | ForEach-Object { Get-ADUser -Identity $_.SamAccountName -Properties LastLogonDate,Enabled,PasswordLastSet } | Select-Object Name,SamAccountName,Enabled,LastLogonDate,PasswordLastSet | Export-Csv "C:\Temp\DomainAdmins-Audit.csv" -NoTypeInformation

Combo 3 — Check replication health and email alert on failure

Windows PowerShell
$failures = Get-ADReplicationFailure -Scope Domain -ErrorAction SilentlyContinue if ($failures) { $body = $failures | Select-Object Server,Partner,FailureCount,LastError | ConvertTo-Html -Fragment | Out-String Send-MailMessage -To "it-alerts@corp.contoso.com" -Subject "AD Replication Failure Detected" -Body $body -BodyAsHtml -SmtpServer "smtp.corp.contoso.com" -From "dc-monitor@corp.contoso.com" Write-Warning "Replication failures detected — alert sent" } else { Write-Host "Replication healthy" -ForegroundColor Green }

Schedule Combo 3 as a Windows Scheduled Task on each DC, running every 4 hours. You will know about replication failures before the helpdesk does.

AD Health Summary — corp.contoso.com
Replication
1 Failure
DC02 → DC01
Locked Accounts
2 Locked
jsmith, sconnor
PDC Emulator
Online
DC01.corp.contoso.com
Stale Computers
47 Objects
>90 days inactive
Tip — Build a daily AD health script: Combine Get-ADReplicationFailure, Search-ADAccount -LockedOut, Get-ADDomainController, and Get-ADComputer -Filter {LastLogonDate -lt $cutoff} into a single script outputting an HTML report. Run as a scheduled task every morning — you walk in each day with a current snapshot of AD health before anyone calls the helpdesk.

References

Share this post
LinkedIn X / Twitter Reddit Bluesky

More from EndpointWeekly

Guides
Active Directory Domain Controller Hardening for Hybrid…
Domain Controllers are the highest-value target in your environment. This post covers…
Scripts
Export and Filter Group Policy Objects to CSV with PowerShell
A simple PowerShell script that lets you search your entire GPO estate by keyword and…
Windows 11
Windows Monthly Updates Explained: LCU, SSU, Patch Tuesday and…
Every month Windows ships updates and most admins do not know the difference between an…