Our Thinking / Field Notes / The Guide

STEP-BY-STEP GUIDANCE / MICROSOFT 365 ADMINISTRATION AND POWERSHELL AUTOMATION

Build a Safe PowerShell Microsoft 365 Audit Report (Read-Only)

Build a read-only Microsoft 365 audit in PowerShell: four read permissions, a session check that blocks write access, and CSV reports on licences, admins, dormant accounts and MFA gaps.

Start here

Use the Microsoft Graph PowerShell SDK and request only four read permissions: LicenseAssignment.Read.All, RoleManagement.Read.Directory, User.Read.All and AuditLog.Read.All. Before collecting anything, check that the session holds nothing beyond those. Then use only Get- cmdlets to export licences, administrator role members, dormant accounts and MFA registration gaps to CSV. None of those calls read passwords, mailbox content or app secrets. The only change in your tenant is the one-off consent for the permissions, which you can revoke afterwards.

What a safe audit report covers - and what it leaves alone

The aim is a report you can hand to a business owner without wincing: who holds administrator roles, which licences are paid for but unused, which enabled accounts look dormant and who has not registered for multi-factor authentication (MFA). Four small CSV files and a short summary. Nothing more.

'Safe' has two halves. The script must not be able to change anything, so we ask Microsoft Graph for read permissions only and check that the session really holds nothing broader. It must also not gather anything sensitive. The calls below return account names, licence counts, role membership, sign-in dates and MFA registration flags. They do not read passwords, mailbox or file content or app registration secrets, and the script avoids Invoke-MgGraphRequest, which can send write requests as easily as reads.

Account names and sign-in dates are still personal data, so treat the output files like an HR spreadsheet. The same least-privilege thinking sits behind the NCSC's Cyber Essentials scheme, which starts from controlling who can access your data and services and at what level. This report is a quick way to see whether that is true in your tenant.

What you need before you start

Most of this is quick to check. The consent step is the one that usually needs somebody else.

  • A computer with PowerShell. PowerShell 7 is the better choice; the Microsoft.Graph module lists 5.1 as its minimum. The current module release on the PowerShell Gallery at the time of writing is 2.41.2.
  • A sign-in that can read the data. Global Reader is listed by Microsoft as a supported role for the licence, role-member and MFA registration calls. Reports Reader is the least privileged role named for sign-in activity.
  • Someone able to grant admin consent to the four permissions if your tenant has not already done so. Microsoft's own quickstart says this typically needs the Privileged Role Administrator role.
  • Microsoft Entra ID P1 or P2 if you want the dormant-account section. Microsoft lists it as a prerequisite for reading last successful sign-in dates. Without it, leave that section out; the rest still works.
  • A folder you can restrict to the people who should see the results. The script writes to a folder in your user profile by default.

Install the modules and sign in with read-only permissions

The full Microsoft.Graph module is large, because it contains hundreds of sub-modules. Installing only the four you use keeps the footprint small and the script's intent obvious. The install is per-user and does not need local administrator rights.

The sign-in is where the safety is decided. Each Graph permission (called a scope in delegated sign-in) is requested by name, so we name the four read permissions and nothing else. Adding -ContextScope Process keeps the sign-in inside this PowerShell window rather than caching it for later sessions.

  1. Install the four modules for your own user account. If PowerShell asks whether to trust the PowerShell Gallery repository, answer according to your own policy. To undo this later, Uninstall-Module removes them.
    powershell
    Install-Module Microsoft.Graph.Authentication, Microsoft.Graph.Identity.DirectoryManagement, Microsoft.Graph.Users, Microsoft.Graph.Reports -Scope CurrentUser
  2. Sign in requesting the four read permissions only.
    powershell
    Connect-MgGraph -Scopes 'LicenseAssignment.Read.All', 'RoleManagement.Read.Directory', 'User.Read.All', 'AuditLog.Read.All' -ContextScope Process -NoWelcome
  3. Complete the browser sign-in. If the permissions have not been approved for your tenant before, the consent screen will ask for an administrator to approve them. Read the list; it should name only read access to licences, directory roles, users and audit logs. Carry on once the terminal returns to a prompt.

Check the session cannot write before you collect anything

Asking for four permissions does not guarantee the session holds only four. Microsoft's own example of Get-MgContext output for the default Microsoft Graph PowerShell sign-in lists a long run of ReadWrite scopes, which shows that permissions granted in earlier sessions can still be in play. If someone previously approved write access for that app, your 'read-only' sign-in may not be read-only at all.

This check compares the session's scopes with an allow-list and stops the script if anything extra appears. It only reads your own session details and changes nothing. A clean run prints the list of scopes and no error. If it stops, the practical fix is a dedicated app registration for audit use, which Microsoft's authentication guide describes (including limiting who can use it); sign in through that app with -ClientId and -TenantId instead of the default one.

powershell
$context = Get-MgContext
$allowed = 'LicenseAssignment.Read.All', 'RoleManagement.Read.Directory', 'User.Read.All', 'AuditLog.Read.All', 'User.Read', 'openid', 'profile', 'email', 'offline_access'
$unexpected = $context.Scopes | Where-Object { $_ -notin $allowed }
if ($unexpected) { throw "Stop: this session also holds $($unexpected -join ', ')" }
$context.Scopes

Collect the data

Run these in the same PowerShell session, one block at a time, or save them together as a script. Every call is a Get- cmdlet. Each block builds a variable and writes one CSV, so you can inspect the result before moving on.

  1. Create the output folder. This makes a new folder called M365-Audit-Report in your user profile and does nothing if it already exists. Restrict access to it now, before any files land there.
    powershell
    $reportFolder = Join-Path $HOME 'M365-Audit-Report'
    New-Item -ItemType Directory -Path $reportFolder -Force | Out-Null
  2. Export licence counts. Get-MgSubscribedSku lists each subscription with purchased and assigned units. The names are Microsoft part numbers such as O365_BUSINESS_PREMIUM; Microsoft publishes a mapping of those to the names shown in the admin centres.
    powershell
    $licences = Get-MgSubscribedSku | ForEach-Object {
        [pscustomobject]@{
            Licence   = $_.SkuPartNumber
            Status    = $_.CapabilityStatus
            Purchased = $_.PrepaidUnits.Enabled
            Assigned  = $_.ConsumedUnits
            Spare     = $_.PrepaidUnits.Enabled - $_.ConsumedUnits
        }
    }
    $licences | Export-Csv -Path (Join-Path $reportFolder 'licences.csv') -NoTypeInformation
  3. List administrator role members. This loops through each activated directory role and records who holds it. Group and service principal members appear too, with the type shown, which is useful when a group quietly holds a privileged role. Note that Microsoft's directoryRole API lists roles activated in the tenant, so roles that have never been used may not appear, and just-in-time eligible assignments are a separate record not covered here.
    powershell
    $adminRoles = foreach ($role in Get-MgDirectoryRole) {
        foreach ($member in Get-MgDirectoryRoleMember -DirectoryRoleId $role.Id) {
            [pscustomobject]@{
                Role              = $role.DisplayName
                MemberType        = $member.AdditionalProperties['@odata.type']
                DisplayName       = $member.AdditionalProperties['displayName']
                UserPrincipalName = $member.AdditionalProperties['userPrincipalName']
            }
        }
    }
    $adminRoles | Export-Csv -Path (Join-Path $reportFolder 'admin-roles.csv') -NoTypeInformation
  4. Fetch users with their sign-in activity and pick out dormant candidates. On a large tenant this can take several minutes because Graph returns sign-in data in pages of up to 500 users; let it finish before moving on. The 90-day cut-off is a starting point (Microsoft suggests 90 to 180 days is a reasonable window for most organisations), so change the number to suit you. A missing date counts as dormant because it means no recorded sign-in; Microsoft notes values can also be blank for activity before April 2020 and the last successful sign-in field was not back-filled before December 2023.
    powershell
    $users = Get-MgUser -All -Property 'id,displayName,userPrincipalName,accountEnabled,userType,createdDateTime,signInActivity'
    $cutoff = (Get-Date).AddDays(-90)
    $dormant = $users | Where-Object {
        $_.AccountEnabled -and $_.UserType -eq 'Member' -and
        (-not $_.SignInActivity.LastSuccessfulSignInDateTime -or $_.SignInActivity.LastSuccessfulSignInDateTime -lt $cutoff)
    } | Select-Object DisplayName, UserPrincipalName, CreatedDateTime, @{ Name = 'LastSuccessfulSignIn'; Expression = { $_.SignInActivity.LastSuccessfulSignInDateTime } }
    $dormant | Export-Csv -Path (Join-Path $reportFolder 'dormant-accounts.csv') -NoTypeInformation
  5. Export MFA registration status. This shows which users have registered an MFA method. It does not read the methods' details such as phone numbers, and Microsoft notes the underlying report does not cover disabled users. The final lines pick out unregistered accounts and the subset that hold an admin role.
    powershell
    $mfa = Get-MgReportAuthenticationMethodUserRegistrationDetail -All
    $mfaGaps = $mfa | Where-Object { -not $_.IsMfaRegistered } | Select-Object UserPrincipalName, UserType, IsAdmin, IsMfaCapable
    $mfaGaps | Export-Csv -Path (Join-Path $reportFolder 'mfa-registration-gaps.csv') -NoTypeInformation

Write the summary and sign out

A one-line-per-measure summary is what a business owner will actually read. The first block builds it from the variables you already have and saves it alongside the CSVs. The second ends the session and clears the cached sign-in for this window, so nothing lingers for the next person to use the machine.

  1. Create and save the summary, then display it. The count of enabled administrators without MFA registration is the line to look at first.
    powershell
    $summary = [pscustomobject]@{
        GeneratedUtc                  = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')
        TotalUsers                    = @($users).Count
        GuestUsers                    = @($users | Where-Object { $_.UserType -eq 'Guest' }).Count
        DormantEnabledMembers90Days   = @($dormant).Count
        AdminRoleAssignments          = @($adminRoles).Count
        UsersWithoutMfaRegistration   = @($mfaGaps).Count
        AdminsWithoutMfaRegistration  = @($mfaGaps | Where-Object { $_.IsAdmin }).Count
    }
    $summary | Export-Csv -Path (Join-Path $reportFolder 'summary.csv') -NoTypeInformation
    $summary
  2. Sign out of Microsoft Graph. Run Get-MgContext afterwards; it should return nothing, confirming no active session remains.
    powershell
    Disconnect-MgGraph

Reading the results without drawing the wrong conclusions

Success looks like this: the four CSVs and summary.csv exist in the folder, the total user count roughly matches what you see in the Microsoft Entra admin centre, and none of the files contain anything you would not want in a spreadsheet emailed around the office. They should not contain passwords, keys or tokens, because nothing in the script reads them. If one does, stop and find out why before sharing it.

The dormant list is a list of people to ask about, not accounts to delete. Microsoft's guidance is to check whether the person still works for you, still needs access and whether the account has another purpose. Shared mailboxes with sign-in enabled, service accounts and seasonal staff all show up. A dormant account nobody recognises is a finding. One called 'scanner' that the photocopier still depends on is a lesson in documentation.

The MFA file shows who has registered a method, not whether your policies require it at sign-in. Conditional Access and security defaults are a separate check and are not part of this report.

Treat the folder as confidential. It contains names, usernames and sign-in dates for your staff. Share the summary with owners; keep the detail files with the administrators who will act on them, and delete them once the clean-up is done.

Running it on a schedule

Unattended running is where read-only habits matter most, because there is no person to notice a consent screen asking for more. Microsoft's SDK supports app-only access for this: you register an application in Microsoft Entra ID, give it the same four permissions as application permissions, have an administrator grant consent and authenticate with a certificate. The sign-in line then looks like the block below, with your own values in place of the YOUR_ tokens.

Two cautions. Application permissions are not limited by any person's role, so they apply tenant-wide; keep the list at the four read permissions and nothing else. And the certificate's private key is now the secret: keep it in the certificate store of the account that runs the task, never in the script or a repository, and set an expiry you will actually remember. Microsoft's SDK can also use a client secret, but a certificate is the better choice because there is no secret string to leak into a script or a log. If the script runs inside Azure, a managed identity removes the need for a certificate altogether; Connect-MgGraph -Identity uses it, though the four Graph permissions must be granted to that identity separately.

Keep the session check from earlier in the scheduled script. It works the same way, because an app-only session lists its application permissions in the same Scopes property.

powershell
Connect-MgGraph -ClientId 'YOUR_APP_ID' -TenantId 'YOUR_TENANT_ID' -CertificateThumbprint 'YOUR_CERT_THUMBPRINT' -NoWelcome

If something goes wrong, and how to undo it

The script only reads, so there is nothing to roll back in your data. The two things you may want to reverse are the consent and the local files.

  • A call fails with an insufficient privileges or forbidden error: check Get-MgContext for the missing permission and confirm your account holds a role such as Global Reader. Consent for a permission and the role to use it are separate requirements.
  • The dormant-account call is refused: the sign-in activity data needs Microsoft Entra ID P1 or P2. Remove that block and the DormantEnabledMembers90Days line from the summary.
  • The administrator list looks short: the role listing covers roles activated in the tenant, and just-in-time eligible assignments are not included. Cross-check privileged roles in the Microsoft Entra admin centre.
  • The session check stops the script: your sign-in holds more than the four permissions. Use a dedicated app registration for audit work rather than adding exceptions to the allow-list.
  • To remove the consent: in the Microsoft Entra admin centre, sign in as at least a Cloud Application Administrator, browse to Enterprise applications, select the application you signed in through, choose Permissions and revoke the permissions listed. Microsoft notes this does not stop users consenting again, and does not end existing sessions.
  • To tidy up locally: run Disconnect-MgGraph, delete the M365-Audit-Report folder and, if you no longer need them, remove the modules with Uninstall-Module.
Technical terms explained
app-only access
A sign-in where an application authenticates as itself, typically with a certificate, and uses the application permissions an administrator approved. No person is involved at run time.
Global Reader
A Microsoft Entra administrator role that can read most configuration and settings across Microsoft 365 but cannot change them.
MFA
Multi-factor authentication: signing in with something more than a password, such as an authenticator app prompt or a security key.
Microsoft Entra ID
Microsoft's cloud identity service, which holds your Microsoft 365 user accounts, groups and administrator roles.
Microsoft Graph
Microsoft's programming interface for reading and managing data in Microsoft 365 and Microsoft Entra ID, including users, licences and directory roles.
scope
The name of a single permission a sign-in asks for, such as User.Read.All. Names ending in .Read.All grant read access; names containing ReadWrite allow changes.

Sources and further reading

KEEP THE CONVERSATION GOING

Want a second opinion on what the report shows?

If the output raises questions about admin accounts, dormant users or MFA coverage in your tenant, we are happy to talk it through.

Contact Rismor