Script to Count and Export Users from Azure AD to CSV with Last Sign-In Information

2 min. readlast update: 09.26.2024

This script connects to Microsoft Graph using specified scopes and retrieves all users in the tenant. It counts the total number of users and exports specific properties—like UserPrincipalName, AccountEnabled, UserType, and last sign-in information—into a CSV file. The script ensures that the output directory exists before exporting and includes error handling to manage permissions or path issues. It is useful for auditing users and their last sign-in activity in an Azure AD environment.

Here is the script:

# Prompt the user to enter Tenant Id or Primary domain
$TenantId = Read-Host "Please enter Tenant Id or Primary domain"

# Define the scopes needed for the Microsoft Graph API permissions
$Scopes = "User.Read.All,AuditLog.Read.All,Directory.Read.All"

# Connect to Microsoft Graph
Connect-MgGraph -Scopes $Scopes

# Count users
$users = Get-MgUser -All
$userCount = $users.Count
Write-Host "Total number of users: $userCount"

# Define the output path
$OutputPath = "C:\temp\UsersExport.csv"

# Check if the directory exists
if (!(Test-Path -Path (Split-Path -Path $OutputPath -Parent))) {
    Write-Host "The directory does not exist. Please check the output path and try again."
    return
}

# Export users with specified properties
try {
    Get-MgBetaUser -All -Property "Id, UserPrincipalName, AccountEnabled, userType, SignInActivity, SignInSessionsValidFromDateTime" | 
    Select-Object Id, UserPrincipalName, AccountEnabled, userType, SignInSessionsValidFromDateTime, 
    @{Name="LastNonInteractiveSignInDateTime"; Expression={$_.SignInActivity.LastNonInteractiveSignInDateTime}},
    @{Name="LastSignInDateTime"; Expression={$_.SignInActivity.LastSignInDateTime}} |
    Export-Csv -Path $OutputPath -NoTypeInformation
    Write-Host "Export successful. The file is located at $OutputPath"
} catch {
    Write-Host "Failed to export users. Please check your permissions and try again."
}

Was this article helpful?