Skip to content
Azure

Microsoft Graph Automation for SharePoint Governance: Where to Start Safely

BP

Billy Peralta

August 25, 2026 · 17 min read

Abstract image of a developer workstation with code on multiple screens

Caspar Camille Rubin on Unsplash

Microsoft Graph SharePoint Governance Azure Automation

Most Microsoft 365 teams hit the same wall: SharePoint sites keep multiplying, external sharing grows, and leadership finally asks for a clear picture of risk and ownership.

You can get a one-time report out of the admin center or Excel. But when you need repeatable governance reporting and targeted cleanup, manual exports and ad-hoc scripts stop working very quickly.

That is where Microsoft Graph becomes attractive. One API for sites, groups, users, reports, and more. It is the natural backbone for serious SharePoint governance automation.

The catch: a badly designed Graph automation can do real damage. An over-privileged app with Sites.FullControl.All and no logging can silently remove access, delete content, or expose data. Support teams are left guessing what happened.

In this guide, I will walk through how to start with Microsoft Graph automation for SharePoint governance safely. The focus is on patterns: permissions, logging, throttling, and support. The code is the easy part.

TL;DR

  • Start with read-only governance scenarios (inventory and reporting) before automating cleanup.
  • Choose delegated vs application permissions deliberately; default to least-privilege application perms for scheduled jobs.
  • Design logging, throttling, and support runbooks before you schedule anything in production.
  • Treat Graph automations as part of your SharePoint governance program, with clear ownership, documentation, and lifecycle.

Table of Contents

Why Microsoft Graph automation matters for SharePoint governance

SharePoint Online governance is not just a policy document. It is a set of repeatable activities:

  • Inventorying sites, owners, and classifications
  • Monitoring external sharing and anonymous links
  • Identifying inactive or abandoned workspaces
  • Finding risky permissions (everyone, external guests, broad groups)
  • Checking that labels, retention, and sharing settings match policy

You can do some of this manually in the SharePoint admin center. But as your tenant grows, you need:

  • Consistency: The same rules applied every week or month
  • Coverage: All sites and workspaces, not just the obvious ones
  • Traceability: Evidence of what was found and what changed

Microsoft Graph is the right tool for this because it provides:

  • A unified API for sites, groups, users, and reports
  • Access to tenant-level reports such as SharePoint usage
  • The ability to run unattended workloads in Azure Functions, Automation, or pipelines

If you already rely on PowerShell for tasks like finding flows that use SharePoint or OneDrive, moving to Graph-based automation is the natural next step.

But more power means more responsibility.

Why unsafe Graph automation is a real risk

When Graph automation goes wrong, it often fails loudly and invisibly at the same time:

  • Loudly, because users suddenly lose access or content disappears
  • Invisibly, because there is no clear audit trail of which script or app made the change

The biggest problem patterns I see:

  • Over-privileged apps: Someone grants Sites.FullControl.All and Directory.ReadWrite.All to a generic app so a script “just works.” Months later, no one remembers what has that level of access.
  • No logging: Scripts run on a schedule, but there is no central log of what they did, which items were changed, or which errors occurred.
  • No throttling strategy: A well-meaning cleanup job hits Graph too hard, gets throttled, and ends up running half-complete. You get partial changes with no obvious pattern.
  • Single-person ownership: The original developer leaves. The app registration, certificates, and source are tied to their account or workstation.
  • No rollback plan: Automation removes access or sites based on bad assumptions, and there is no fast, scripted way to put things back.

This is how governance automation turns into governance debt. You may have policies, but your scripts are operating outside your governance model.

Real-World Scenario

Let us walk through a composite example that looks a lot like what I have seen in real tenants.

A global organisation has grown to thousands of SharePoint sites and Teams. Compliance is worried about oversharing, so the SharePoint admin team is asked to produce a monthly report of:

  • Sites with anyone links
  • Sites with guest members
  • Sites with no active owner

The first few reports are built manually from the admin center and exported to Excel. It takes several days every month, so one of the admins creates a PowerShell script that calls Microsoft Graph to:

  1. List all sites
  2. For each site, find the connected Microsoft 365 group and its owners
  3. Flag sites that have guests or no owner
  4. Save the result to CSV on a file share

The script works well, so they add a second script to “fix” the problems:

  • Remove guest users from any group where no internal owner is found
  • Change sharing settings to disable anyone links on all flagged sites

To make it unattended, they register an Azure AD app with Sites.FullControl.All and Group.ReadWrite.All application permissions, store a client secret in the script file, and schedule it on a job server.

Six months later:

  • The helpdesk receives sporadic tickets from project teams whose external partners suddenly lose access.
  • A key external-facing site for a large client quietly has its sharing tightened, breaking workflows and increasing friction.
  • Security asks for evidence of what was changed and by whom. The SharePoint admin team has to reverse-engineer the scripts and log into the job server to piece together what happened.

There are several problems here, but the root ones are:

  • Cleanup actions were automated before there was a robust reporting and review process.
  • The Graph app had broad, tenant-wide write permissions with no separation of duties.
  • There was no central logging or support runbook.

A safer, more supportable design for the same outcome would be:

  1. A read-only Graph app with Sites.Read.All and Directory.Read.All application permissions, used to produce a governance report in a SharePoint list or Log Analytics.
  2. A review and approval step where site owners and compliance sign off the proposed changes.
  3. A separate, more privileged app with Sites.Selected and Group.ReadWrite.All that is allowed to change settings only on approved sites.
  4. Automation runs in Azure (Function or Automation Account) with logs streaming to Application Insights and a standard support runbook.

The business still gets risk reduction, but IT keeps control, visibility, and the ability to explain and reverse changes.

A safe first automation: read-only SharePoint governance report

If you are just getting started with Microsoft Graph automation for SharePoint governance, begin with a read-only inventory. For example:

Generate a weekly report of all SharePoint sites with their URL, template, connected group, classification, last activity date, and whether they have at least two internal owners.

This kind of report unlocks a lot:

  • Input to your inactive site policy (tying into strategies like in Managing inactive SharePoint Online sites)
  • Early detection of ownerless or high-risk sites
  • Better conversations with business owners about lifecycle and clean-up

Suggested architecture

A simple, safe pattern looks like this:

  1. Azure AD app registration

    • Application permissions: Sites.Read.All, Group.Read.All, Directory.Read.All (or a subset)
    • Admin consent granted through your normal approval process
    • Secret or certificate stored in Azure Key Vault
  2. Execution environment

    • Azure Function, Azure Automation runbook, or a pipeline in Azure DevOps or GitHub Actions
    • Runs on a schedule (for example, weekly)
  3. Data collection using Microsoft Graph

    • Query sites via Graph sites and groups endpoints
    • For each site, resolve the connected Microsoft 365 group and its owners
    • Enrich with usage or activity data (from Graph reports or other sources)
  4. Output and storage

    • Store a snapshot in a SharePoint list, Azure Table, or CSV in a governance library
    • Push structured logs to Log Analytics or Application Insights

Here is a minimal PowerShell example using the Microsoft Graph PowerShell SDK just to show the pattern:

Connect-MgGraph -Scopes 'Sites.Read.All','Group.Read.All','Directory.Read.All'
Select-MgProfile -Name 'v1.0'

# Basic example: list sites. Replace 'contoso' with part of your domain or name.
$sites = Get-MgSite -Search 'contoso'

$sites | Select-Object Id, WebUrl, DisplayName

In production, you would use app-only authentication with certificate credentials, controlled in Azure Key Vault, and add paging, rate limiting, and logging. The important point is that this first automation is read-only and focused on visibility.

Once you have consistent, trusted reports, you can start designing safe cleanup workflows on top.

Delegated vs application permissions

Understanding Graph permission models is crucial before you automate anything.

Delegated permissions

Delegated permissions are used when a user is present and has signed in. The app acts on behalf of that user, and its effective permissions are the intersection of:

  • The delegated scopes the app has
  • The rights the signed-in user already has in the tenant

Typical delegated scenario for governance:

  • A SharePoint admin runs an interactive PowerShell script to generate a one-off report.

Pros:

  • Changes are constrained by the admin’s own permissions.
  • Actions are easier to correlate with a user in audit logs.

Cons:

  • Not suitable for unattended, scheduled jobs.
  • Permissions are tied to individual admins, which is fragile for long-term automation.

Application permissions

Application permissions are used for daemon or background processes. The app acts as its own identity, independent of any user. It can be granted very broad rights, such as Sites.Read.All or Sites.FullControl.All.

Typical application permission scenario for governance:

  • A scheduled Azure Function runs nightly to inventory sites and store results in a central location.

Pros:

  • Ideal for scheduled, non-interactive jobs.
  • Not tied to specific admin accounts.

Cons:

  • Potentially very powerful; a misconfigured app can access or change almost anything it is allowed to.
  • Requires a more formal approval and review process.

Practical guidance

For SharePoint governance automation:

  • Use delegated permissions for:

    • Early experimentation and prototypes
    • One-off reports run by an admin
  • Use application permissions for:

    • Scheduled reporting and monitoring
    • Any automation that must run without user interaction

When you move to application permissions, apply these patterns:

  • Prefer Sites.Selected instead of Sites.FullControl.All whenever possible, especially for write operations.
  • Split apps by purpose. Do not give a single app both full read and full write across the tenant.
  • Capture admin consent decisions as part of your governance records.

Decision framework for Graph governance automation

Before you build a new Graph-based automation, run it through a simple RACE model:

R = Risk level of the action

  • Read-only reporting is low risk.
  • Changing sharing settings or permissions is medium to high risk.
  • Deleting sites or content is very high risk.

A = Audience impact

  • Internal admin-only changes (for example, adding metadata) have limited impact.
  • Changes that affect business users or external partners have wider impact.

C = Control and rollback

  • Can you easily reverse the change with another script or process?
  • Do you have a record of exactly what was changed?

E = Execution model

  • Delegated vs application permissions
  • Scheduled vs manually triggered

For each proposed automation, write down R, A, C, and E. Use this to decide:

  • Which environment it runs in first (dev, test, pilot, production)
  • Required level of logging and approvals
  • Whether you need a manual approval step before changes are applied

If you cannot answer C (control and rollback) confidently, it is too early to automate write operations.

Technical recommendations

1. Design your automation identities

Treat each Graph-based automation as its own service identity:

  • Create a dedicated Azure AD app registration per major automation domain, not one giant app for everything.
  • Use certificate-based authentication instead of client secrets for long-running automations.
  • Store credentials in Azure Key Vault and access them via managed identities.

This reduces blast radius and makes security reviews simpler.

2. Apply least privilege to Graph permissions

For SharePoint governance scenarios:

  • Start with Sites.Read.All and Directory.Read.All for reporting.
  • Add Group.Read.All if you need owner/member information for Microsoft 365 groups.
  • For write operations, prefer Sites.Selected combined with Group.ReadWrite.All.

Map each permission to a specific requirement. If you cannot justify a permission in plain language, do not request it.

3. Build logging in from day one

A governance automation without logging is a risk multiplier.

At minimum, log for every run:

  • Automation name and version
  • Run identifier (GUID)
  • Start and end time
  • Identity used (app id)
  • Counts: how many objects were processed, changed, skipped, and failed
  • For write actions, the before and after values for key properties

A simple PowerShell pattern for structured logging:

$runId = [guid]::NewGuid()
$logEntry = [PSCustomObject]@{
    RunId     = $runId
    Timestamp = (Get-Date).ToString('o')
    Action    = 'InventorySites'
    SiteCount = $sites.Count
    Errors    = $errors.Count
}

$logEntry | ConvertTo-Json -Depth 3 | Out-File -FilePath $logPath -Append

In Azure, send this to Application Insights or Log Analytics instead of a flat file. The key is that any support engineer can reconstruct what happened during a run.

4. Respect throttling and service limits

Graph has throttling limits per endpoint and per tenant. For large tenants:

  • Implement paging and process items in batches.
  • Respect the Retry-After header when you call Graph via raw HTTP.
  • Avoid pulling full inventories unnecessarily; use delta queries or last-modified timestamps when available.
  • Schedule heavy jobs outside of known peak business hours.

Throttling-aware design avoids half-finished cleanups and hard-to-explain side effects.

5. Treat cleanup as a separate, reviewable stage

Do not jump straight from report to automatic cleanup.

A safer pattern:

  1. Inventory job writes potential clean-up actions into a SharePoint list (for example, site, detected issue, proposed fix).
  2. Site owners or governance admins review and approve items.
  3. A separate job runs and applies changes only to approved rows.

This pattern works very well for permission cleanup and external sharing risk reduction, especially when combined with practices from SharePoint site permissions best practices.

6. Align with your existing tooling

You might already have tools like a SharePoint Permission Visualizer or other reporting solutions.

Use Graph to:

  • Feed richer data into those dashboards
  • Replace manual exports from admin centers
  • Standardise how you access site, group, and user information

Graph should extend your governance ecosystem, not compete with it.

Common mistakes and risks

Here are some of the most common issues I see in real tenants when Graph automation is introduced.

  1. Using personal app registrations

    • The app is created under an individual admin’s account. When they leave or change roles, no one can maintain or review the app.
  2. Granting broad write permissions too early

    • Sites.FullControl.All or Directory.ReadWrite.All is granted just to get a script working. Over time, people forget why.
  3. Storing secrets in scripts or on servers

    • Client secrets and certificates are stored directly in PowerShell files or on VMs. This ignores basic secret management practices.
  4. Running production jobs from admin laptops

    • Scheduled tasks on personal machines or ad-hoc scripts become de facto production automations. There is no central control or visibility.
  5. No environment separation

    • The same app and script are used in dev, test, and prod. A small change is tested on a live tenant with real data.
  6. Ignoring error handling and partial failures

    • Scripts assume every Graph call succeeds. When throttling or transient errors occur, the script stops midway and leaves inconsistent state.
  7. No communication with support and security teams

    • Helpdesk and security are unaware of the automation. When issues occur, they have no idea it might be related to a scheduled job.
  8. Treating automation as a one-time project

    • No one is assigned as long-term owner. There is no review cycle for permissions, scope, or logic.

Avoiding these mistakes is just as important as writing clean code.

Governance and lifecycle considerations

Graph-based automation should be part of your SharePoint governance plan, not a side project.

Key lifecycle questions:

  • Ownership: Who owns each automation from a business perspective and a technical perspective?
  • Onboarding and offboarding: What happens to the app registration and credentials when admins change roles?
  • Reviews: How often do you review the app’s permissions and logic? Who signs off?
  • Change management: How are changes to the automation tested, approved, and deployed?

Document each automation in your governance register with:

  • Purpose and description
  • Data sources and Graph permissions
  • Execution schedule and environment
  • Logging and monitoring locations
  • Support runbook and escalation path

If you are formalising this from scratch, it is worth aligning with your broader SharePoint governance consulting approach so that automation, permissions, and policies evolve together.

Migration and adoption considerations

Graph automation is particularly powerful around migrations and major adoption pushes.

Before or after a migration (for example, from file shares or SharePoint Server), you can use Graph to:

  • Detect sites with risky or overly broad permissions, building on ideas from The hidden cost of messy SharePoint permissions.
  • Identify inactive or duplicate sites created during migration.
  • Validate that labels, retention, and sharing settings were applied as planned.

Be cautious about timing:

  • Do not run aggressive cleanup jobs while users are still stabilising post-migration.
  • Treat cleanup as a second phase once usage patterns are clearer.

From an adoption perspective, the more you automate governance reporting and clean-up, the more consistently you can support new experiences like Copilot or SharePoint Advanced Management without manual chasing.

Business impact

When Microsoft Graph automation is designed well for SharePoint governance, you get tangible benefits across multiple teams.

For IT and SharePoint admins

  • Fewer ad-hoc scripts and manual exports
  • Faster, more accurate answers to questions such as “who owns this site” or “which sites are externally shared”
  • Less time firefighting permission issues caused by manual clean-up

For security and compliance teams

  • Clear, auditable view of what governance automation is doing
  • Better evidence for audits and incident response
  • Ability to move from spot-checks to continuous monitoring

For support and service desk

  • Fewer unexplained access issues from rogue or fragile scripts
  • Clear runbooks that include checking automation logs when incidents occur

For business owners and leadership

  • Confidence that governance policies are actually being enforced
  • More predictable risk profile as the tenant grows
  • Ability to support new capabilities (like AI and Copilot) without opening unknown access risks

Poorly designed automation has the opposite effect: it increases risk while giving a false sense of control. The design work you put in up front directly reduces the likelihood and impact of security incidents and service outages later.

Practical checklist

Use this checklist as a starting point for any new Microsoft Graph automation for SharePoint governance:

  1. Define a read-only first scenario (inventory or reporting) before any cleanup.
  2. Document the purpose of the automation in plain language and add it to your governance register.
  3. Choose the execution model: delegated for interactive admin tools, application permissions for scheduled jobs.
  4. Create a dedicated app registration per automation domain; avoid one app that does everything.
  5. Request least-privilege Graph permissions and record why each permission is needed.
  6. Store secrets or certificates securely in Azure Key Vault; never in script files or on local machines.
  7. Design structured logging (run id, counts, errors, before/after values) and choose a central log store.
  8. Plan for throttling and scale: batching, paging, and reasonable schedules for large tenants.
  9. Separate reporting and remediation: treat cleanup as a second-stage automation with approvals.
  10. Pilot in a non-production or limited-scope environment with a subset of sites.
  11. Create a support runbook and brief your helpdesk and security teams.
  12. Review permissions and logic regularly (for example, quarterly) and capture approvals.
  13. Align with broader governance initiatives, including permissions clean-up, inactive site management, and Copilot readiness.

If you work through this list for each automation, your Graph usage will support governance rather than undermining it.

Final thoughts

Microsoft Graph is the right backbone for serious SharePoint governance automation. It lets you move from manual, one-off reports to repeatable, trusted monitoring and targeted clean-up.

The technical barrier is lower than ever, but the governance barrier still matters: permissions, logging, throttling, ownership, and lifecycle. Those are what separate a helpful automation from a high-risk script.

Start with low-risk, high-value reporting scenarios. Prove your patterns for identity, logging, and support. Then layer in carefully controlled cleanup and enforcement.

If you would like a second set of eyes on your approach, or you are planning to expand your use of Microsoft Graph in your tenant, I offer practical SharePoint governance consulting that often includes reviewing and designing safe automation patterns.

A short design review can save you from months of firefighting later.

handshake

Need help applying this in a real Microsoft 365 environment?

I help organizations turn technical fixes into maintainable SharePoint, SPFx, and Power Platform solutions that internal teams can support.

timeline 16+ years experience verified Microsoft certified apartment Government & enterprise

Free SharePoint planning resource

Planning a SharePoint migration or governance cleanup?

Download the SharePoint Migration & Governance Readiness Checklist to review migration scope, permissions, governance, Teams/OneDrive strategy, retention, and Copilot readiness.

Download the Checklist
BP

Billy Peralta

SharePoint & Microsoft 365 Specialist • 16+ Years Experience

If you have questions about your SharePoint environment, feel free to reach out.

Need help applying this in a real Microsoft 365 environment?

I help organizations turn technical fixes into maintainable SharePoint, SPFx, and Power Platform solutions that internal teams can support.