LLI Wiki — My Digital Knowledge Base

PowerShell and Active Directory: Get-ADUser examples

Find users, expired accounts, groups, CSV exports and photos with the ActiveDirectory cmdlets.

A collection of Get-ADUser and related Active Directory cmdlet examples (module ActiveDirectory, part of RSAT).

Find users

# One user by sAMAccountName, with extra properties
Get-ADUser -Filter {samAccountName -eq "jdoe"} -Properties sAMAccountName,Title,manager

# Parameter help
help Get-ADUser -Parameter identity

# Users whose name starts with Joe
Get-ADUser -Filter {name -like "Joe*"}

# Wildcards on name
Get-ADUser -Filter {name -like 'j*w*'}

Filtering on the server with -Filter is more efficient than retrieving everything and filtering in the pipeline. Compare:

Get-ADUser -Filter * | Where-Object {$_.GivenName -like 'j*' -and $_.Surname -like 'W*'}

Measure-Command {Get-ADUser -Filter * | Where-Object {$_.GivenName -like 'j*' -and $_.Surname -like 'W*'}}

Count and list accounts

# Total number of accounts
Get-ADUser -Filter {SamAccountName -like "*"} | Measure-Object

# Active (enabled) accounts
Get-ADUser -Filter {Enabled -eq "True"} | Select-Object SamAccountName,Name,Surname,GivenName | Format-Table

# Enabled accounts whose password has expired
Get-ADUser -Filter {Enabled -eq $True} -Properties passwordExpired | Where-Object {$_.PasswordExpired}

# Users who have not changed their password in the last 90 days
$90_Days = (Get-Date).AddDays(-90)
Get-ADUser -Filter {(passwordlastset -le $90_days)}

Groups

# All groups a user belongs to
Get-ADPrincipalGroupMembership username | Select-Object name

# Same, from the memberOf attribute
Get-ADUser jdoe -Properties memberof | Select-Object -ExpandProperty memberof

# Add a user to a group
Add-ADGroupMember -Identity "GroupName" -Member username

Export to CSV

Active accounts with an e-mail address:

Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Format-Table

Address book export, which can be imported into mail clients such as Outlook or Thunderbird:

Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Export-Csv -NoTypeInformation -Encoding utf8 -Delimiter "," $env:temp\address_list.csv

For a list of accounts in a CSV file (a user column), get each user's company and save it to another CSV that Excel can open:

Import-Csv c:\ps\users_list.csv | ForEach-Object {
    Get-ADUser -Identity $_.user -Properties Name, Company |
        Select-Object Name, Company |
        Export-Csv c:\ps\users_ad_list.csv -Append -Encoding UTF8
}

Photo

Save a user's thumbnailPhoto attribute to a JPEG file:

$usr = Get-ADUser jdoe -Properties thumbnailPhoto
$usr.thumbnailPhoto | Set-Content jdoe.jpg -Encoding byte

Local accounts and SIDs

wmic useraccount get name,sid

Notes

Mastodon LLIMastodon SocialFosstodon