We recently had a client who wanted to audit their Azure users. They wanted a list containing

  • Display name
  • First name
  • Last name
  • When the account was created
  • When the account was last used (logged in to)
  • If the account is synced from on-prem or not
  • and most importantly what Azure roles were assigned to each user

After several hours of polishing, mostly by our script guru Khalid Abdullahi, we came up with the script below.



# Install Microsoft.Graph module only if it is not already installed
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) {
    Install-Module -Name Microsoft.Graph -Force
}

# Increase the function capacity because there are soooo many functions in Graph
$MaximumFunctionCount = 16384

# Import the Microsoft.Graph.Users module
Import-Module Microsoft.Graph.Users

# Connect to Microsoft Graph which will prompt you for credentials
$scopes = @("User.Read.All", "Directory.Read.All", "RoleManagement.Read.Directory")
Connect-MgGraph -Scopes $scopes

# Get all users with the desired properties
$users = Get-MgUser -All

# Initialize an array to store user information
$customUsers = @()

# Loop through each user and retrieve detailed information using Microsoft Graph API
foreach ($user in $users) {
    $userDetails = Invoke-MgGraphRequest -Method Get -Uri "https://graph.microsoft.com/v1.0/users/$($user.Id)?`$select=displayName,givenName,surname,userPrincipalName,createdDateTime,signInActivity,onPremisesSyncEnabled"
    
    # Get user's assigned roles
    $roleAssignments = Invoke-MgGraphRequest -Method Get -Uri "https://graph.microsoft.com/v1.0/users/$($user.Id)/memberOf"
    $rolesArray = $roleAssignments.value | Where-Object { $_.'@odata.type' -eq '#microsoft.graph.directoryRole' } | ForEach-Object { $_.displayName }
    $roles = $rolesArray -join ", "

    $customUser = [PSCustomObject]@{
        DisplayName           = $userDetails.displayName
        FirstName             = $userDetails.givenName
        LastName              = $userDetails.surname
        Username              = $userDetails.userPrincipalName
        CreatedDate           = if ($userDetails.createdDateTime) { [DateTime]::Parse($userDetails.createdDateTime).ToString('yyyy-MM-dd') } else { $null }
        LastInteractiveLogin  = if ($userDetails.signInActivity.lastSignInDateTime) { $userDetails.signInActivity.lastSignInDateTime -replace 'T.*','' } else { $null }
        OnPremisesSyncEnabled = $userDetails.onPremisesSyncEnabled
        AssignedRoles         = $roles
    }

    $customUsers += $customUser
}

# Sort the users by DisplayName
$customUsers = $customUsers | Sort-Object DisplayName

# Output to the screen
$customUsers | Format-Table -AutoSize

# Export to CSV
$customUsers | Export-Csv -Path "C:\temp\azure-users.csv" -NoTypeInformation



0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *