PowerShell – Exporting a List of Azure AD Users

From time to time you’ve likely been asked to perform some sort of export of users from AAD, a task that’s not made particularly simple via the portal which lacks any sort of export option.

Luckily, with PowerShell this is made quite simple.

The Script

Requirements

Description

The script below will connect to a defined azure tenant and export a list of all users. Be sure to fill in the Tenant ID and Path variables at the top.

<# Variables #>

$TenantID = '*Tenant ID*' #Defines what Directory to connect to, can be found in Azure by viewing the Directories list
$path = '*Path*' #Define where the file csv will save to, EG. C:\Users\User\Desktop

<# End of Variables #>

# Connect to Azure
Connect-AzureAD -TenantId $TenantID ## Found under name of tenant in Azure

# Get the name of the tenant
$TenantName = Get-AzureADTenantDetail

# Get the basic list of users
$Users = Get-AzureADUser
$UserDetails = @()

# For each user retrieve the details (hidden in extended properties)
$progressCount = 0
for($i = 0; $i -le $Users.Count; $i++) {
    # Just writes status
    Write-Progress -Id 0 -Activity "Retrieving User " -Status "$progressCount of $($Users.Count)" -PercentComplete (($progressCount / $Users.Count) * 100)
    $UserDetails += (Get-AzureADUser)[$i] | Select-Object -Property *

    $progressCount++
}
# Stops the progress report
Write-Progress -Id 0 -Activity " " -Status " " -Completed

# Display the Properties
$UserDetails | Select DisplayName, AccountEnabled, JobTitle, Mobile, UserPrincipalName, UserType | Format-Table

try {
    $UserDetails | Select DisplayName, AccountEnabled, JobTitle, Mobile, UserPrincipalName, UserType | Export-Csv -Path $path + "\Azure-Export_$($TenantName.DisplayName).csv" -NoTypeInformation
    Write-Host "Exported all user details" -ForegroundColor Green
} catch {
    Write-Host "$error" -ForegroundColor red
}
Advertisement

2 thoughts on “PowerShell – Exporting a List of Azure AD Users

  1. [SOLVED]:
    – change (1): under “# Get the basic list of users”
    $Users = Get-AzureADUser -All $True
    – change (2) under “# For each user retrieve the details (hidden in extended properties)”
    $UserDetails += (Get-AzureADUser -All $True)[$i]

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.