Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Administration

The Active Directory PowerShell Module

Manage Active Directory with PowerShell: Get-ADUser, filters versus LDAP filters, creating users from a CSV, group and OU tasks, stale-account reports, the AD Recycle Bin and safe scripting habits.

The graphical tools (Active Directory Users and Computers, ADUC) are fine for one change. For anything repeated, large or risky, you want PowerShell. The ActiveDirectory module talks to a domain controller through the Active Directory Web Services (ADWS, TCP 9389), so it works from any admin workstation with the Remote Server Administration Tools (RSAT) and does not need a logon to the DC.

This lesson explains the verbs and nouns, the two filter languages, bulk creation, reporting and safety habits. PowerShell and a live domain are not available on this site, so every cmdlet is a read-only example. Python stand-ins let you practise the logic: translating filters and validating a CSV import before any real change.

Getting started

POWERSHELL
Import-Module ActiveDirectory          # loaded automatically in modern PowerShell
Get-Command -Module ActiveDirectory | Measure-Object
Get-ADDomain
Get-ADForest
Get-ADDomainController -Filter *

The module follows PowerShell naming: Get-, New-, Set-, Remove-, Move- plus a noun such as ADUser, ADComputer, ADGroup, ADOrganizationalUnit, ADObject, ADGroupMember. Use Get-Help Get-ADUser -Examples to learn each one.

Reading objects

POWERSHELL
Get-ADUser -Identity alice
Get-ADUser -Identity alice -Properties mail, department, lastLogonDate, memberOf
Get-ADUser -Filter 'Department -eq "Finance" -and Enabled -eq $true' -SearchBase "OU=Staff,DC=example,DC=com"
Get-ADUser -LDAPFilter '(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))'

Important behaviours:

  • By default only a default property set comes back (name, DN, SID, sAMAccountName, enabled and a few more). Ask for others with -Properties, or -Properties * for everything (slow on big queries).
  • -Filter uses PowerShell expression syntax (-eq, -like, -and) with attribute names, and the cmdlet translates it to LDAP. -LDAPFilter takes the raw LDAP filter syntax from the protocol chapter. Use -LDAPFilter when you need bitwise matching rules or exact control.
  • Always use -SearchBase and, where relevant, -SearchScope to limit the query; an unqualified -Filter * pulls the entire domain.
  • Single-quote the filter string so PowerShell does not expand $variables early; to use a variable inside it, use a script block or build the string explicitly.
  • -Identity accepts a DN, GUID, SID or sAMAccountName.

Common tasks

POWERSHELL
# create
New-ADUser -Name "Alice Wong" -SamAccountName awong -UserPrincipalName [email protected] `
  -GivenName Alice -Surname Wong -Path "OU=Staff,DC=example,DC=com" `
  -AccountPassword (Read-Host -AsSecureString "Password") -Enabled $true -ChangePasswordAtLogon $true

# change
Set-ADUser awong -Department "Finance" -Title "Analyst"
Set-ADAccountPassword awong -Reset -NewPassword (Read-Host -AsSecureString)
Unlock-ADAccount awong
Disable-ADAccount awong

# groups
Add-ADGroupMember -Identity "Finance-Readers" -Members awong
Get-ADGroupMember "Finance-Readers" -Recursive | Select Name, SamAccountName

# move
Move-ADObject (Get-ADUser awong).DistinguishedName -TargetPath "OU=Finance,OU=Staff,DC=example,DC=com"

# remove (consider the Recycle Bin first)
Remove-ADUser awong -Confirm

Never pass plain-text passwords on the command line or in scripts; use Read-Host -AsSecureString, a secret store or randomly generated values you hand over securely.

Translating -Filter to an LDAP filter

Understanding both syntaxes helps a lot when a filter returns the wrong thing. This stand-in translates the simplest PowerShell filter forms (-eq, -like, -ne, -and, -or) to LDAP. It is deliberately small and not a full parser.

Python PowerShell filter to LDAP filter (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A real cmdlet also maps Enabled to the bitwise userAccountControl rule, handles -ge/-le, dates and -not; this keeps the shape visible.

Bulk creation from a CSV (validate first)

A common job: HR sends a spreadsheet and you must create 200 accounts. The risky part is bad data, so validate everything before the first New-ADUser, produce a report, and only then run (and use -WhatIf for a dry run):

POWERSHELL
Import-Csv .\newhires.csv | ForEach-Object {
  New-ADUser -Name "$($_.First) $($_.Last)" -SamAccountName $_.Sam -UserPrincipalName "$($_.Sam)@example.com" `
    -Path $_.OU -AccountPassword $pw -Enabled $true -WhatIf
}

The Python stand-in below does the validation part: pre-Windows-2000 sAMAccountName is limited to 20 characters with a set of forbidden characters, names must be unique, and OUs must be known.

Python Validate a new-hire list before import

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reports administrators use all the time

POWERSHELL
# accounts that have not signed in for 90 days (lastLogonTimestamp replicates every ~14 days)
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly | Select Name, LastLogonDate

# accounts with passwords that never expire
Get-ADUser -Filter 'PasswordNeverExpires -eq $true -and Enabled -eq $true' -Properties PasswordNeverExpires

# locked-out accounts
Search-ADAccount -LockedOut

# empty groups, delegation, privileged members
Get-ADGroup -Filter * | Where-Object { -not (Get-ADGroupMember $_) }
Get-ADComputer -Filter 'TrustedForDelegation -eq $true' -Properties TrustedForDelegation
Get-ADGroupMember "Domain Admins" -Recursive

# export
... | Export-Csv report.csv -NoTypeInformation

lastLogonTimestamp is only updated if the old value is older than about 14 days, so it is accurate to two weeks only; the precise lastLogon attribute is not replicated and must be read from every DC.

The AD Recycle Bin

Once enabled (irreversible, forest functional level 2008 R2 or higher), deleted objects keep all their attributes, including group membership, and can be restored:

POWERSHELL
Enable-ADOptionalFeature 'Recycle Bin Feature' -Scope ForestOrConfigurationSet -Target example.com
Get-ADObject -Filter 'isDeleted -eq $true -and Name -like "Alice*"' -IncludeDeletedObjects
Restore-ADObject -Identity <ObjectGUID>

See backup and recovery for lifetimes and what happens when the Recycle Bin is off.

Safe scripting habits

  • -WhatIf and -Confirm on anything that changes data; log what you did.
  • Test in a lab or on a pilot OU first, and keep a backup of what you are about to change (Get-ADUser ... | Export-Clixml).
  • Select properties and filter on the server, not with Where-Object after fetching the whole directory.
  • Target one DC (-Server dc1.example.com) for a multi-step script so reads see your writes immediately instead of racing replication.
  • Run with the least privileged account that has the delegated rights, and avoid saved credentials in scripts.
  • Turn on PowerShell script block logging so administrative actions are auditable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should Get-ADUser queries include -SearchBase?

    A search base keeps the query small and fast and the result set predictable.
  2. 2. Which parameter returns attributes beyond the default set?

    -Properties lists the extra attributes to retrieve; the default set contains only common ones.
  3. 3. Why is lastLogonTimestamp unsuitable for exact 'last seen' times?

    The 14-day update rule reduces replication traffic but makes the attribute approximate.
  4. 4. What should you do before running a bulk New-ADUser loop?

    Validation and -WhatIf reveal bad data and wrong targets before any object is created.

Summary

  • The ActiveDirectory module uses ADWS and offers Get/New/Set/Remove/Move cmdlets per object type.
  • -Filter is PowerShell syntax, -LDAPFilter is raw LDAP; always use a search base and request only needed properties.
  • Validate bulk imports first, use -WhatIf, and target a single DC for multi-step scripts.
  • Reports for stale, locked and risky accounts are the everyday value; the Recycle Bin protects against mistakes.

Next: Replication, Sites and FSMO Roles