Skip to content

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

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

Section titled “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

Section titled “Define the scopes needed for the Microsoft Graph API permissions”

$Scopes = “User.Read.All,AuditLog.Read.All,Directory.Read.All”

Connect-MgGraph -Scopes $Scopes

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

$OutputPath = “C:\temp\UsersExport.csv”

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 }

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.” }