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 GraphConnect-MgGraph -Scopes $Scopes
# Count users$users = Get-MgUser -All$userCount = $users.CountWrite-Host "Total number of users: $userCount"
# Define the output path$OutputPath = "C:\temp\UsersExport.csv"
# Check if the directory existsif (!(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 propertiestry { 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."}
Help Center