Using Active Directory with PowerShell

This post is a personalized go-to reference for my most used Active Directory PowerShell commands. Might be useful for you, might not 😋

Get a list of all users that are members of a group.

get-adgroupmember "group_name" -recursive | ft

or

Get-ADGroupMember -identity "group_name" -Recursive | Get-ADUser -Property DisplayName | Select Name

Export memberships of a user in AD

# Fetches the memberships of a user in AD

$username = Read-Host -Prompt 'Enter username' 
Get-ADPrincipalGroupMembership $username | select name | Out-File "$username.csv"

Removes extra whitespace at the end of every line
$content = Get-Content "$username.csv"
$content | Foreach {$_.TrimEnd()} | Set-Content "$username.csv"

# Opens the file
Invoke-Item -Path "$username.csv"

Export list of expired users in AD:

# This script will generate a list of user accounts that have 
# expired before this day. These users will not have access to 
# their user account unless the expiration date is changed.
Search-ADAccount -Credential $Creds -AccountExpired -UsersOnly -ResultPageSize 2000 -resultSetSize $null| Select-Object Name, AccountExpirationDate | Out-File "Expired users.csv"
# Opens the file
Invoke-Item -Path "Expired users.csv"

Export all users in AD:

Import-module activedirectory | get-aduser -filter * | Export-Csv -Encoding unicode "C:\your directory\Users.csv"
Invoke-Item -Path "C:\your directory\Users.csv"
Write-Host "Press any key to continue ..."

Sources: https://stackoverflow.com/questions/5072996/how-to-get-all-groups-that-a-user-is-a-member-of