Microsoft 365 | PowerShell Security Audit – Part 1: Identity and Access

Microsoft 365 | PowerShell Security Audit – Part 1: Identity and Access

Check MFA, roles, guests & mailboxes

A few clicks through the admin center won’t reveal a compromised tenant. Spot checks in the web interface are error-prone, provide no historical benchmarks, and obscure the interconnections between identities, devices, and data.

This is exactly where attackers strike: at the weakest link, usually accounts with weak authentication. A reliable security audit therefore requires raw data, not aggregated portal views.

Experience from hardening projects reveals a clear pattern: most successful attacks on Microsoft 365 environments exploit a handful of the same vulnerabilities. Missing MFA enforcement, open legacy protocols, uncontrolled app permissions, lack of device compliance, and disabled audit logging. All five can be checked via PowerShell long before they appear in the portal.

This audit covers 80 checkpoints and is divided into three parts.

Part 1 covers identity and MFA, Conditional Access, privileged roles, guests, and Exchange mailboxes. Part 2 focuses on email protection, collaboration, devices, and apps, while Part 3 concludes with data governance, compliance, and monitoring.

Each check can run independently and be executed individually. Alternatively, the relevant components for production can be bundled in a collective script or Azure Automation runbook.

Identity, MFA, and Risk

1. Entra ID MFA and phishing resistance

License:Entra ID Free (Basic), Entra ID P1 (detailed logs)

The mere status of 'MFA-registered' falls short. AitM (Adversary in the Middle) attacks intercept session cookies via proxy, bypassing classic push notifications. What matters is the specific method per account, as a user relying solely on SMS or voice calls is vulnerable to SIM swapping and social engineering. In Graph, both SMS and voice are categorized under the type phoneAuthenticationMethod, so detecting phone is sufficient for identifying weak methods. The goal is to roll out FIDO2 or passkeys and strictly disable phone-based methods.

# Modul: Microsoft.Graph.Identity.SignIns, Microsoft.Graph.Users
Connect-MgGraph -Scopes "UserAuthenticationMethod.Read.All","User.Read.All" -NoWelcome
$users = Get-MgUser -All -Property Id, UserPrincipalName
$mfaReport = foreach ($user in $users) {
    $methods = Get-MgUserAuthenticationMethod -UserId $user.Id
    $types = foreach ($m in $methods) { ($m.AdditionalProperties["@odata.type"] -replace "#microsoft.graph.","") }
    [PSCustomObject]@{ UserPrincipalName = $user.UserPrincipalName; Methods = ($types -join ", ") }
}
$mfaReport | Where-Object { $_.Methods -match "phone" } | Format-Table   # Befund: schwache Phone- oder SMS-Methode

2. Global Authentication Methods Policy

As long as SMS or voice calls remain enabled tenant-wide, user training alone is ineffective because weak methods remain selectable. The Authentication Methods Policy serves as the lever to cleanly deprecate these legacy methods technically. If a method is set to enabled but should no longer be used, it must be set to disabled.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
(Get-MgPolicyAuthenticationMethodPolicy).AuthenticationMethodConfigurations |
    Select-Object Id, State | Sort-Object Id | Format-Table   # Befund: Id "Sms" oder "Voice" mit State "enabled"

3. Security Defaults Status

Security Defaults are Microsoft’s baseline protection for tenants without Conditional Access—both cannot be active at the same time. The setting only makes sense in context: Without CA policies, IsEnabled must be True; with productive CA policies, False is correct. A tenant without Security Defaults and without CA is left exposed.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
(Get-MgPolicyIdentitySecurityDefaultEnforcementPolicy).IsEnabled

4. Legacy authentication in sign-in logs

License: Entra ID P1

Legacy protocols such as IMAP, POP3, and SMTP Basic Auth authenticate outside token-based policies, meaning MFA does not apply. Even with active blocking, analyzing sign-in data reveals whether connection attempts persist, indicating misconfigured clients or targeted attacks. Grouping by legacy client immediately highlights problem areas.

Connect-MgGraph -Scopes "AuditLog.Read.All" -NoWelcome
$since = (Get-Date).AddDays(-7).ToString("yyyy-MM-ddTHH:mm:ssZ")
$legacyApps = @("IMAP4","POP3","SMTP","MAPI","Other clients","Exchange ActiveSync","AutoDiscover")
$signins = Get-MgAuditLogSignIn -Filter "createdDateTime ge $since" -All
$signins | Where-Object { $_.ClientAppUsed -in $legacyApps } |
    Group-Object ClientAppUsed | Select-Object Name, Count

5. Inactive member accounts

License: Entra ID P1

It’s not just guests that become orphaned. An internal account with no sign-ins for months is either a former employee whose offboarding is stuck or a forgotten service account—both are attack surfaces with no business value. Any account inactive for over 90 days needs review. Without P1, SignInActivity stays empty, making the results useless.

Connect-MgGraph -Scopes "AuditLog.Read.All","User.Read.All" -NoWelcome
$cut = (Get-Date).AddDays(-90)
$members = Get-MgUser -Filter "userType eq 'Member' and accountEnabled eq true" -Property UserPrincipalName, SignInActivity -All
$members | Where-Object { $null -ne $_.SignInActivity.LastSignInDateTime -and [datetime]$_.SignInActivity.LastSignInDateTime -lt $cut } |
    Select-Object UserPrincipalName, @{N="LastSignIn";E={$_.SignInActivity.LastSignInDateTime}}

6. Risk users from Identity Protection

License: Entra ID P2

Identity Protection assesses sign-in risk based on signals such as leaked credentials, IP reputation, and atypical locations. If an account is marked as atRisk and no automated remediation is triggered, a potential account takeover may go unaddressed. Every hit must be investigated or forced to change the password via a risk policy.

Connect-MgGraph -Scopes "IdentityRiskyUser.Read.All" -NoWelcome
Get-MgRiskyUser -Filter "riskState eq 'atRisk'" -All |
    Select-Object UserPrincipalName, RiskLevel, RiskState, RiskLastUpdatedDateTime

Conditional Access and sessions

7. Durchsetzung der bedingten Zugriffssteuerung

License: Entra ID P1

Conditional Access policies define the hard system boundaries of the tenant. A policy in "Report Only" mode blocks not a single attack—it merely logs; in Graph, this state is represented by the value enabledForReportingButNotEnforced. Since the web portal often obscures nesting and exclusions, the state of all policies belongs in a flat overview.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
Get-MgIdentityConditionalAccessPolicy |
    Select-Object DisplayName, State |
    Sort-Object State | Out-GridView   # Befund: State "enabledForReportingButNotEnforced"

8. Trusted Named Locations

Many organizations exclude corporate IP addresses from MFA. When a company switches providers, these IP ranges often remain as 'Trusted Locations,' and whoever takes over these old IPs gains a direct bypass of your authentication policies. Every trusted location therefore requires periodic confirmation by the network department.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
Get-MgIdentityConditionalAccessNamedLocation -All |
    Where-Object { $_.AdditionalProperties.isTrusted -eq $true } |
    Select-Object DisplayName, ModifiedDateTime,
        @{N="IPRanges";E={ ($_.AdditionalProperties.ipRanges.cidrAddress) -join ", " }}

9. Session Control: Sign-in Frequency and Persistent Browser

License: Entra ID P1

Stolen session tokens are only valuable for as long as the session remains valid. Without Sign-in Frequency and without disabling Persistent Browser on unmanaged devices, a captured token remains usable for days. To see which policies actually set session controls, look at the SessionControls.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
Get-MgIdentityConditionalAccessPolicy |
    Select-Object DisplayName,
        @{N="SignInFrequency";E={$_.SessionControls.SignInFrequency.Value}},
        @{N="PersistentBrowser";E={$_.SessionControls.PersistentBrowser.Mode}} |
    Format-Table

Privileged roles and PIM

10. Privileged Identity Management Control

License: Entra ID P2

Permanent administrative permissions undermine any security concept. A compromised Global Admin with persistent rights leads to immediate tenant takeover, whereas PIM enforces just-in-time access. You need to identify permanently assigned roles (type "Assigned" with no expiration date), which you then convert into eligible assignments. Results are only available in a PIM-enabled tenant; for direct non-PIM assignments, use Get-MgRoleManagementDirectoryRoleAssignment.

Connect-MgGraph -Scopes "RoleManagement.Read.Directory" -NoWelcome
$aa = Get-MgRoleManagementDirectoryRoleAssignmentSchedule -ExpandProperty "Principal,RoleDefinition" -All
$aa | Where-Object { $_.AssignmentType -eq "Assigned" -and $_.ScheduleInfo.Expiration.Type -eq "noExpiration" } |
    Select-Object @{N="UPN";E={$_.Principal.AdditionalProperties.userPrincipalName}}, @{N="Role";E={$_.RoleDefinition.DisplayName}} |
    Sort-Object Role | Format-Table -AutoSize

11. Number of global administrators

Global Admins have unrestricted access to all data and settings; every additional account increases the blast radius in case of compromise. Microsoft recommends two to four dedicated accounts, strictly separated from day-to-day accounts. If the number exceeds this, each account must be justified or removed.

Connect-MgGraph -Scopes "RoleManagement.Read.Directory" -NoWelcome
$ga = Get-MgDirectoryRole -Filter "displayName eq 'Global Administrator'"
$members = Get-MgDirectoryRoleMember -DirectoryRoleId $ga.Id -All
"Global Admins: $(@($members).Count)"   # Empfehlung: 2 bis 4 dedizierte Konten
$members | ForEach-Object { $_.AdditionalProperties.userPrincipalName }

12. Monitoring Break-Glass Accounts

License: Entra ID P1

Break-glass admin accounts are intentionally excluded from Conditional Access and MFA to ensure that a misconfiguration does not block access. These accounts have global admin rights, so every sign-in indicates either an IT emergency or a security incident. If you find a login without an associated emergency ticket, treat it as a critical incident.

Connect-MgGraph -Scopes "AuditLog.Read.All" -NoWelcome
$breakGlass = @("notfalladmin1@deinedomain.de","notfalladmin2@deinedomain.de")
$since = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ")
Get-MgAuditLogSignIn -Filter "createdDateTime ge $since" -All |
    Where-Object { $_.UserPrincipalName -in $breakGlass } |
    Select-Object CreatedDateTime, UserPrincipalName, IpAddress, Status | Format-Table

13. Local administrators on joined devices

On Windows clients joined to Entra ID, the local device administrator role grants local admin rights on every corporate notebook—if an account with this role is compromised, it enables widespread ransomware distribution. The trap lies in the name: With the Entra rebrand, the role was renamed from *Azure AD Joined Device Local Administrator* to *Microsoft Entra Joined Device Local Administrator*. A filter on the display name therefore returns empty and falsely reports zero matches. Only the fixed role template ID remains stable.

Connect-MgGraph -Scopes "RoleManagement.Read.Directory" -NoWelcome
# Stabil ueber die roleTemplateId, bei eingebauten Rollen entspricht sie der roleDefinition-Id
$deviceAdminRoleId = "9f06204d-73c1-4d4c-880a-6edb90606fd8"
Get-MgRoleManagementDirectoryRoleAssignment -Filter "RoleDefinitionId eq '$deviceAdminRoleId'" -ExpandProperty Principal |
    Select-Object @{N="User";E={$_.Principal.AdditionalProperties.userPrincipalName}}, PrincipalId | Format-Table

14. End-user app registration

If end users are allowed to create app registrations, uncontrolled service principals with their own secrets and API access are created. The target state is: Only admins should register apps. If AllowedToCreateApps is set to True, the barrier is open.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
(Get-MgPolicyAuthorizationPolicy).DefaultUserRolePermissions.AllowedToCreateApps   # Befund, wenn True

Guests and external collaboration

15. Inactive B2B guest accesses

License: Entra ID P1

Orphaned external identities are a common issue. A service provider finishes a project, their account remains active, and if their home tenant is compromised weeks later, the attacker gains direct B2B access. Anything inactive for over 90 days is flagged for deactivation. Without P1, SignInActivity remains empty, causing every guest to appear falsely inactive.

Connect-MgGraph -Scopes "AuditLog.Read.All","User.Read.All" -NoWelcome
$cut = (Get-Date).AddDays(-90)
$guests = Get-MgUser -Filter "userType eq 'Guest'" -Property Id, UserPrincipalName, SignInActivity -All
$guests | Where-Object {
    $null -eq $_.SignInActivity.LastSignInDateTime -or [datetime]$_.SignInActivity.LastSignInDateTime -lt $cut
} | Select-Object UserPrincipalName, @{N="LastSignIn";E={$_.SignInActivity.LastSignInDateTime}}

16. Guest Invitation Policy

If AllowInvitesFrom is set to everyone, any employee can invite arbitrary external accounts. Guest accounts then persist in groups, teams, and sites even after collaboration has ended. Restricting this to admins or dedicated inviters curbs the growth of external identities.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
(Get-MgPolicyAuthorizationPolicy).AllowInvitesFrom   # Befund, wenn "everyone"

17. Cross-Tenant Access Settings

The Cross-Tenant Access Settings control trust between Entra ID environments. If inbound trust is set too permissively, your tenant will accept MFA and compliance assertions from external tenants without verification. If the query returns `IsServiceDefault = True`, Microsoft’s default settings remain unchanged, which rarely aligns with the actual collaboration model.

Connect-MgGraph -Scopes "Policy.Read.All" -NoWelcome
Get-MgPolicyCrossTenantAccessPolicyDefault |
    Select-Object IsServiceDefault, InboundTrust | Format-List

Exchange Online and mailboxes

18. Mailbox delegation (FullAccess)

License: Exchange Online Plan 1

Full access permissions create opaque networks for lateral movement. A compromised assistant mailbox often grants full access to executive communications, while the AutoMapping feature obscures these accesses in Outlook. The goal is to identify non-inherited FullAccess rights outside of system accounts.

Connect-ExchangeOnline -ShowBanner:$false
$mailboxes = Get-Mailbox -ResultSize Unlimited
foreach ($mb in $mailboxes) {
    Get-MailboxPermission -Identity $mb.UserPrincipalName |
    Where-Object { $_.User -notlike "NT AUTHORITY\*" -and $_.IsInherited -eq $false -and $_.AccessRights -match "FullAccess" } |
    Select-Object Identity, User, AccessRights
}

19. Send As delegation

Those with SendAs permissions on another mailbox can send emails in that mailbox’s name—a classic vector for internal CEO fraud. These permissions are not part of the mailbox permission object but are read via Get-RecipientPermission. This closes the gap left by FullAccess alone.

Connect-ExchangeOnline -ShowBanner:$false
foreach ($mb in (Get-Mailbox -ResultSize Unlimited)) {
    Get-RecipientPermission -Identity $mb.UserPrincipalName |
    Where-Object { $_.Trustee -notlike "NT AUTHORITY\*" -and $_.AccessRights -contains "SendAs" } |
    Select-Object Identity, Trustee, AccessRights
}

20. Hidden auto-forwarding rules at mailbox level

After an account takeover, attackers set up forwarding rules, causing incoming emails to be silently redirected to external addresses. At the mailbox level, this is configured in the ForwardingSmtpAddress property. That’s one half of the problem—the other is covered in the next point.

Connect-ExchangeOnline -ShowBanner:$false
Get-Mailbox -ResultSize Unlimited |
    Where-Object { $null -ne $_.ForwardingSmtpAddress } |
    Select-Object UserPrincipalName, ForwardingSmtpAddress, DeliverToMailboxAndForward

21. Inbox rules with external forwarding

More common than mailbox forwarding is silent exfiltration via inbox rules that aren’t stored in the mailbox object. You read them per mailbox using Get-InboxRule and check the actions ForwardTo, ForwardAsAttachmentTo, and RedirectTo. With many mailboxes, this process takes time—schedule it outside peak hours.

Connect-ExchangeOnline -ShowBanner:$false
foreach ($mb in (Get-Mailbox -ResultSize Unlimited)) {
    Get-InboxRule -Mailbox $mb.UserPrincipalName |
        Where-Object { $_.ForwardTo -or $_.ForwardAsAttachmentTo -or $_.RedirectTo } |
        Select-Object @{N="Mailbox";E={$mb.UserPrincipalName}}, Name, Enabled, ForwardTo, RedirectTo
}

22. Outbound Spam: Auto-Forwarding Mode

Organization-wide, the outbound spam policy determines whether automatic external forwarding is allowed. The value On enables auto-forwarding despite individual mailbox rules, while Automatic currently corresponds to Off because Microsoft has changed this for all customers. If a policy is set to On, it requires justification or should be reverted.

Connect-ExchangeOnline -ShowBanner:$false
Get-HostedOutboundSpamFilterPolicy | Select-Object Name, AutoForwardingMode   # Befund, wenn "On"

23. Automatic forwarding to remote domains

Admins define exceptions for external forwarding via Remote Domains. A Remote Domain with AutoForwardEnabled = True is an approved data leak and must be documented restrictively. Every instance requires a business justification.

Connect-ExchangeOnline -ShowBanner:$false
Get-RemoteDomain | Where-Object { $_.AutoForwardEnabled -eq $true } |
    Select-Object DomainName, AutoForwardEnabled, AutoReplyEnabled | Format-Table

24. Mail flow rules with SCL bypass

Transport rules override Exchange Online Protection's spam filter decisions. A rule that sets the Spam Confidence Level to -1 for specific senders bypasses all security mechanisms, and once the sender's domain is compromised, malware ends up unfiltered in the inbox. Such whitelists should be replaced by modern tenant allow/block lists.

Connect-ExchangeOnline -ShowBanner:$false
Get-TransportRule | Where-Object { $_.SetSCL -eq -1 } |
    Select-Object Name, State, Description | Format-Table

25. Legacy protocols at mailbox level

Even if Conditional Access blocks legacy authentication across the network, POP3 and IMAP4 still exist on the mailboxes, and a faulty exclusion in a CA policy can expose them again instantly. Defense in depth means: disable the protocols directly at the mailbox level. A closed port cannot be attacked.

Connect-ExchangeOnline -ShowBanner:$false
Get-CASMailbox -ResultSize Unlimited |
    Where-Object { $_.PopEnabled -eq $true -or $_.ImapEnabled -eq $true } |
    Select-Object DisplayName, PopEnabled, ImapEnabled | Format-Table

26. Modern Authentication in Exchange Online

Microsoft has already disabled Basic Auth for legacy protocols, but the organization-wide switch for Modern Auth should still be set to True because it secures token-based sign-in for Outlook. If the query returns False, a component of modern authentication is missing.

Connect-ExchangeOnline -ShowBanner:$false
Get-OrganizationConfig | Select-Object OAuth2ClientProfileEnabled   # Soll: True

27. Enable mailbox auditing organization-wide

Without mailbox auditing, there is no trace after an incident of who accessed which email and when. Mailbox auditing has been enabled by default since 2019, but it can be disabled organization-wide, and the global switch AuditDisabled overrides any setting on individual mailboxes. False means enabled, True is a finding.

Connect-ExchangeOnline -ShowBanner:$false
Get-OrganizationConfig | Select-Object AuditDisabled   # Befund, wenn True

28. Connection Filter: IP Allow List

An IP allow list in the connection filter bypasses entire IP ranges from spam filtering. Properly maintained, this is legitimate; a forgotten or overly broad list allows emails from these ranges to be delivered unchecked. Every entry requires a current justification.

Connect-ExchangeOnline -ShowBanner:$false
Get-HostedConnectionFilterPolicy | Select-Object Name, IPAllowList, EnableSafeList | Format-List

29. Mark external emails

A visible tag on emails from external sources isn’t a technical blocker, but it noticeably reduces the success rate of phishing and CEO fraud because users immediately see the context. External Tagging can only be enabled via PowerShell—there’s no toggle in the Exchange Admin Center. If Enabled is set to False, this awareness layer is missing.

Connect-ExchangeOnline -ShowBanner:$false
Get-ExternalInOutlook | Select-Object Identity, Enabled, AllowList   # Befund, wenn Enabled = False

Prerequisites & Authentication

These notes apply to all three parts of the series. The pitfalls determine whether the checkpoints can establish a connection at all, and they almost always lie in the environment, not in the code.

The common denominator: Each of the major modules brings its own .NET assemblies, PowerShell loads an assembly exactly once per session and cannot unload it. If two versions of the same library collide—because submodules are at different update levels or because two modules include the same DLL—the first cmdlet that requires the other version will fail.

The most important consequence upfront: once a session is in this state, no repair command will help—only a fresh window. You clean up the module state and restart PowerShell.

The foundation is a consistent module state. Important: Run the cleanup and installation block in a fresh session where no Connect-MgGraph has been executed yet. A loaded module cannot be uninstalled; otherwise, Uninstall-Module will respond with "currently in use".

# In einer frischen Session, bevor ein Connect ein Modul laedt
# Altlasten entfernen (schliesst die alten Graph.Core-DLLs aus PnP-Altversionen ein)
Get-Module Microsoft.Graph* -ListAvailable | Uninstall-Module -AllVersions -Force -ErrorAction SilentlyContinue
Uninstall-Module PnP.PowerShell -AllVersions -Force -ErrorAction SilentlyContinue

# Konsistente Versionen installieren
Install-Module Microsoft.Graph -Scope CurrentUser -Force
Install-Module ExchangeOnlineManagement -Scope CurrentUser -Force   # mindestens 3.7.2 wegen -DisableWAM
Install-Module MicrosoftTeams -Scope CurrentUser -Force
Install-Module PnP.PowerShell -Scope CurrentUser -Force
Install-Module Microsoft.Online.SharePoint.PowerShell -Scope CurrentUser -Force

# Einmalig: eigene Entra-App fuer PnP registrieren, ClientId notieren
Register-PnPEntraIDAppForInteractiveLogin -ApplicationName "PhinIT-Audit" -Tenant "deintenant.onmicrosoft.com"

Microsoft Graph: Version conflict between submodules

`Connect-MgGraph` runs successfully, but the first `Get-Mg*` cmdlet returns: *"Could not load file or assembly 'Microsoft.Graph.Authentication, Version=2.x.0.0' ... Assembly with same name is already loaded"*.

The issue is caused by multiple versions of the Microsoft.Graph.* modules installed in parallel: Connect-MgGraph loads one version of Microsoft.Graph.Authentication, while the cmdlet from Microsoft.Graph.Users expects another, and the already loaded version takes precedence.

First, check if there are indeed multiple versions.

Get-Module Microsoft.Graph.Authentication -ListAvailable | Select-Object Name, Version

More than one version is the issue. Cleanup runs in a fresh window, and it must happen before any Connect-MgGraph or Get-Mg* reloads the assembly. Disconnect-MgGraph and Remove-Module do not unload the DLL—only closing the console releases it. So: close the window, open a new one, and uninstall first. Removing just the meta-module isn’t enough; the submodules remain, so you must iterate over all of them.

Get-InstalledModule Microsoft.Graph* | ForEach-Object {
    Uninstall-Module -Name $_.Name -AllVersions -Force -ErrorAction SilentlyContinue
}
Install-Module Microsoft.Graph -Scope CurrentUser -Force -AllowClobber

If you don’t want to reinstall right now, load the desired version in a fresh session before connecting—it’ll win the race. This is a patch, not a substitute for a clean module state.

Import-Module Microsoft.Graph.Authentication -RequiredVersion 2.35.0
Connect-MgGraph -Scopes "User.Read.All" -NoWelcome

Microsoft Graph and PnP together: shared Graph.Core assembly

Once Graph and PnP.PowerShell run in the same session, you’ll encounter "Could not load type AzureIdentityAccessTokenProvider" or a similar Microsoft.Graph.Core error. PnP includes its own, often older Microsoft.Graph.Core.dll. If it loads first, it overwrites the Graph SDK’s version, causing the Get-Mg* cmdlets to fail. The solution is separation: run Graph checks in one session and PnP/SharePoint checks in another. If you need both in a single collection script, encapsulate the PnP portion in its own background job or runspace to prevent it from pulling its assemblies into the main session.

Exchange Online: WAM Broker and Module Version

During Connect, a NullReferenceException may occur in RuntimeBroker, or -DisableWAM may be rejected as an "unsupported parameter". As of module version 3.7.0, Web Account Manager is the default, which causes issues in consoles without a window context, and the -DisableWAM switch was only introduced in 3.7.2. You update the module to at least 3.7.2, append -DisableWAM only when necessary, and execute Connect in a fresh session. The v3 module is REST-based and rarely conflicts with Graph, so you can safely add the Exchange checks to the Graph checks in the same session.

SharePoint: Two Modules, Two Runtimes

The SPO module `Microsoft.Online.SharePoint.PowerShell` is built on .NET Framework and runs natively only in Windows PowerShell 5.1. In PowerShell 7, it launches a hidden Windows PowerShell 5.1 background session via the compatibility layer.

Import-Module Microsoft.Online.SharePoint.PowerShell -UseWindowsPowerShell

In contrast, PnP.PowerShell requires PowerShell 7. For this reason, neither should be in the same session as the Graph checks, and ideally not with each other either. On top of that, there’s the authentication hurdle: since 09.09.2024, Connect-PnPOnline -Interactive requires its own Entra app via -ClientId, as Microsoft has decommissioned the PnP multi-tenant app. The registration can be handled once with Register-PnPEntraIDAppForInteractiveLogin; alternatively, PnP reads the ClientId from the environment variables ENTRAID_APP_ID or ENTRAID_CLIENT_ID.

Teams, Security & Compliance and the Three Basic Rules

The MicrosoftTeams module is relatively self-contained and usually coexists well with a parallel Exchange session. The checks for DLP, retention, labels, audit retention, and alert policies from Part 3 run via Security & Compliance PowerShell, for which you open a dedicated session using `Connect-IPPSSession`—this cmdlet includes the ExchangeOnlineManagement module. Three rules keep the entire audit conflict-free. First, one task per session: Graph and Exchange together, PnP and SPO separately. Second, PowerShell 7 for Graph and PnP, Windows PowerShell 5.1 only where the SPO module requires it. Third, if an assembly error occurs, do not continue in the same session—instead, clean up the module state and open a fresh window. Loaded assemblies persist until the console is closed, and any further attempts will run into the same error.

Conclusion after the first 30 audits

Identity is the first and most critical line of defense for a Microsoft 365 tenant. Those who analyze MFA methods, Conditional Access, privileged roles, and guest and mailbox configurations as raw data will spot the gaps that a single click through the admin center obscures. The 29 checkpoints in this section cover the attack paths most frequently exploited in real tenant compromises—from weak SMS authentication to silent mailbox forwarding.

This covers the foundation, but a tenant is more than just identity and email. In Part 2, we’ll examine email threat protection with SPF, DKIM, and DMARC, as well as Defender for Office 365, sharing settings in SharePoint, OneDrive, and Teams, device compliance in Intune, and app permissions that enable OAuth consent phishing. These are checkpoints 30 to 58.

Share:
No comments yet

Be the first to start the discussion with a helpful comment.

Leave a comment

Comments are reviewed briefly before they are published — factual, respectful and to the point is just right here.

Your email address will not be published.