A Cleaner Way to Connect PowerShell to SharePoint Online

image

Connect-PnPOnline with a browser sign-in is fine when you’re sitting at the keyboard. It becomes a problem the moment you’re not. The script that worked beautifully on your laptop refuses to run unattended. The scheduled job that was meant to tidy up orphaned sites overnight quietly does nothing, because it’s still waiting for someone to type a password. And the moment conditional access tightens on the admin account you’ve been quietly using for automation, every script that touches SharePoint behaves like it’s been thrown out a window.

The fix has existed. The setup hasn’t.

Certificate-based app authentication for SharePoint Online has been supported by Microsoft for years. The mechanics are well documented. The trouble has always been the assembly — generate a cert, export the public key, register an app in Entra ID, paste the right GUIDs in the right boxes, find Sites.FullControl.All in the API permissions list, grant admin consent, copy the thumbprint somewhere you won’t lose it, and verify the tenant ID in three different places along the way. By the time you’ve finished, you’ve forgotten which client you were doing it for.

So I’ve written a script that does the whole sequence end to end:

  • Generates a self-signed RSA-2048 certificate in your local certificate store

  • Creates the Entra ID app registration

  • Uploads the certificate and grants Sites.FullControl.All with admin consent

  • Provisions the service principal and adds Application.Read.All on Graph so the app can read its own metadata back

  • Resolves your tenant’s SharePoint root URL automatically from the Graph verified-domains call

  • Saves tenant, app ID, site URL, and thumbprint into a JSON profile so future connections need almost no parameters

What’s normally half an hour of clicking between Entra, the SharePoint admin centre, and a Notepad full of half-remembered GUIDs runs in about ninety seconds.

I’ve been written a new script — https://github.com/directorcia/Office365/blob/master/o365-connect-pnp-cert.ps1

with full documentation here – https://github.com/directorcia/Office365/wiki/Connect-to-SharePoint-Online-with-Certificates

What the Script Actually Does

There are two modes, controlled by switches.

-GenerateLocalCertificate creates a self-signed RSA-2048 certificate in your current user’s certificate store, exports the public key as a .cer file, and optionally exports a password-protected .pfx. By default it’s valid for two years. That’s the local side of the handshake.

-UseCertificateAuth is the everyday mode. You tell it which tenant to connect to — or let it look up the details in a profile map file — and it signs into Exchange Online using that certificate. No password. No browser. No MFA dialog.

The clever bit is the third option: combining -GenerateLocalCertificate with -ProvisionEntraApp -Tenant 'contoso.onmicrosoft.com'. In a single run, the script will generate the local certificate, authenticate to Microsoft Graph via a device-code flow, create the Entra ID app registration if it doesn’t exist, upload the certificate, grant Exchange.ManageAsApp and Application.Read.All with admin consent, create the matching service principal, sign you into Exchange Online to add the app to the Organization Management role group, and save the tenant, app ID, and certificate thumbprint to a JSON profile file so future connections don’t need any of those parameters.

Getting Started

If you’re new to certificate auth, the first run is the one that matters. Drop the script onto an admin machine, open PowerShell, and run:

.\o365-connect-pnp-cert.ps1 -GenerateLocalCertificate -ProvisionEntraApp -Tenant 'yourtenant.onmicrosoft.com'

You’ll be prompted to sign in — via device code for the Graph permissions (which if you use the –copydevicecodetoclipboard, option will put the required device code straight into the clipboard to paste into the request). You need a Global Admin account.

Where this earns its keep across a client base

After that first run, connecting to a tenant looks like this:

.\o365-connect-pnp-cert.ps1 -UseCertificateAuth -Tenant ‘contoso.onmicrosoft.com’

No password. No browser. No MFA prompt. The profile file is the bit that pays you back across an MSP book. One script lives in your tooling folder, each client has its own certificate and entry in the JSON map, and Task Scheduler can finally drive things like site collection audits, sharing reports, lifecycle cleanup on Teams-connected sites, and external-user reviews without anyone watching it run. Filter by tenant or site URL on the command line and the same script services twenty different customers without you ever editing it.

One honest caveat

When you’ve just provisioned a brand-new app, give Entra fifteen to thirty minutes for the role grants to replicate before your first cert-based connect. It’s the single most common reason a fresh setup looks broken when it isn’t. The script flags this on the way out, but it’s worth saying twice.

Why Certificates Beat Passwords

The security argument is the easy one. A certificate’s private key never leaves the machine that generated it. Nothing crosses the wire that an attacker could intercept and replay. There’s no shared secret to rotate across a team, no admin password sitting in a vault that someone might extract, and no MFA bypass to engineer because the flow doesn’t involve a user account at all.

If the certificate is ever compromised, you remove the key credential from the app registration and the access is gone — no password reset required, no impact on any human admin account.

The script enforces TLS 1.2, refuses to assign RBAC if the PnP session has landed in the wrong tenant, warns when the certificate is within thirty days of expiry, and keeps the device-code value off the clipboard by default to avoid leaks on RDP or shared sessions.

The change is a quiet one. You stop thinking about who is signing in and start thinking about which certificate is presenting itself. Once your SharePoint automation is no longer at the mercy of someone else’s MFA settings or a password rotation policy, the kind of work you’re willing to schedule expands. That’s the real win — not the ninety seconds saved on setup, but the chores you finally get around to doing.

New Publication – Achieving SMB1001:2026, M365 PowerShell Automation Guide

blog

https://directorcia.gumroad.com/l/smb1001-2006-ps

Achieving SMB1001:2026. Microsoft 365 PowerShell Automation Guide

Unlock the highest level of security, compliance, and operational efficiency with the definitive PowerShell automation guide for SMBs, MSPs, and IT professionals.

Why Choose This Guide?
  • Production-Ready Automation: Deploy fully-scripted, repeatable, and auditable solutions for every major security and compliance control in Microsoft 365 Business Premium—no more guesswork or manual errors.

  • Comprehensive Coverage: Includes 12 essential technology management controls (firewall, antivirus, patching, BitLocker, application allow-listing, EDR, and more) and 18 access management controls (account lifecycle, MFA, privileged access, email security, etc.), all mapped to the SMB1001:2026 standard.

  • Built for Professionals: Perfect for Managed Service Providers (MSPs), IT administrators, and security teams managing multiple tenants or seeking to implement infrastructure-as-code and configuration-as-code best practices.

  • Audit-Ready Evidence: Every script is designed to generate compliance evidence, validation reports, and audit artifacts—making regulatory audits and client reporting effortless.

  • Idempotent & Safe: All automation is designed to be safely re-run, ensuring consistent results and minimizing risk in live environments.

  • Best Practice Guidance: Each control includes not just scripts, but also implementation notes, validation steps, and operational best practices—so you’re never left wondering “what’s next?”

  • Legal & Licensing Clarity: Single-user, non-commercial license with clear terms; organizational and commercial use available by arrangement.

Key Benefits
  • Achieve and Maintain Compliance: Streamline your journey to SMB1001:2026 Level 5 (Diamond) compliance with proven, field-tested automation.

  • Reduce Risk: Enforce least-privilege, automate patching and security baselines, and block legacy threats—dramatically lowering your attack surface.

  • Save Time and Resources: Replace hours of manual configuration with one-click, script-driven deployments and validations.

  • Centralize and Standardize: Manage all tenants, devices, and users from a single, consistent playbook—ideal for MSPs and multi-tenant environments.

  • Stay Audit-Ready: Generate and maintain all the evidence you need for regulatory, insurance, or client audits—automatically.

Who Should Buy This Guide?
  • MSPs managing Microsoft 365 environments for multiple clients.

  • IT Administrators seeking robust, repeatable, and documented security/compliance deployments.

  • Security Teams needing automated compliance validation and evidence collection.

  • Organizations implementing infrastructure-as-code and aiming for best-in-class security posture.

What’s Inside?
  • Step-by-step PowerShell scripts for every control, with validation and compliance checks.

  • Modular structure for easy adoption—implement what you need, when you need it.

  • Quick reference tables, evidence checklists, and compliance calendars.

  • Guidance for integrating with HR, ITSM, Azure Key Vault, and Microsoft Graph APIs.

  • Best practices for onboarding, offboarding, privileged access, password management, backup, recovery, and more.


Don’t just meet compliance—automate it, prove it, and stay ahead of evolving threats.
Purchase the SMB1001:2026 PowerShell Automation Guide and transform your Microsoft 365 security and compliance operations today!

See all the titles available at – https://directorcia.gumroad.com/

PowerShell script to extract Exchange Online data for your own AI analysis

A while ago I wrote a script that reads Microsoft 365 security information and exports it to a JSON data file. The idea is that you can take this data file and use it with your AI of choice. I have now developed a similar script but for Exchange Online information.

Screenshot 2026-02-01 213211

When you run the script it will connect to Exchange online and extract the information from a variety of locations

Screenshot 2026-02-01 213303

It will produce 2 output JSON files in the parent directory. The standard data file can be quite large, in the case above it is around 15MB. The other file produced is more ‘compact’ around 100 – 200KB

Screenshot 2026-02-01 213701

You can then take either of these JSON files and feed them into you AI system of choice. The above shows you the result when I fed it into Copilot Researcher.,

Screenshot 2026-02-01 214046

and I even got a nice Word document when I fed it into Claude online.

You can download the script here:

https://github.com/directorcia/Office365/blob/master/Analysis/Exchange/exo-extract.ps1

and find the documentation here:

https://github.com/directorcia/Office365/wiki/Extract-Exchange-Online-information

as well as a long prompt you can use with your Ai of choice here:

https://github.com/directorcia/Office365/blob/master/Analysis/Exchange/prompt-long.txt

Given that email systems are typically at the highest security risk, this script shoudl allow you to quickly and easily evaluate its posture as well as giving you a range of improvement suggestions.

Unlocking Microsoft 365 Security: How I Automated AI-Powered Risk Analysis with PowerShell

Video URL – https://www.youtube.com/watch?v=gyPXlI6GHCo

In this video, I walk you through my exclusive PowerShell script that transforms Microsoft 365 security management. Watch as I extract real-time security data from my Microsoft 365 tenant, summarize it, and seamlessly upload it to a custom AI Foundry agent powered by GPT-5. You’ll see how I authenticate using Azure AD, leverage model routing for the best AI analysis, and generate a detailed, actionable HTML security report—complete with risk assessments, prioritized recommendations, and remediation guides. This tool is available only to subscribers, so if you want to supercharge your Microsoft 365 security with AI automation, this is a must-watch! Drop your questions in the comments and discover what’s possible when PowerShell meets next-gen AI. See the blog post at – https://blog.ciaops.com/2026/01/22/co…

Essential 8 AI report via PowerShell

Screenshot 2026-01-25 112744

I recently provided a PowerShell script to extract M365 data for your own AI analysis. Also as part of that I provided two recommended prompts you can use to generate a report based on that data. I have now added an Essential 8 prompt you can use to generate a detailed Essential 8 analysis and report, which you an find here:

https://github.com/directorcia/Office365/blob/master/Analysis/Secure%20Score/prompt-e8.txt

Screenshot 2026-01-25 112919

You can see the result of this prompt in the images provided, which in this case was used with Copilot Researcher with Claude.

You can of course, use this prompt with any AI you prefer and just use it as a starting point and customise to suit your needs

If you have any further suggestions for prompts with this extract security data please let me know.

PowerShell script to extract M365 security data for your own AI analysis

blog

I wrote about how I have now integrated PowerShell and AI recently:

https://blog.ciaops.com/2026/01/22/combining-powershell-and-ai-for-m365-security-analysis/

In that example, I use my own agent developed in Azure AI Foundry to analyse security data extracted from Microsoft 365. In there I did offer free access to the script and my Foundry AI agent for analysis. However, I do appreciate that many people are hesitant to allow a ‘foreign’ AI system to evaluate private M365 security data.

Therefore, I have created another script that will simply extract your M365 security data and put it into a local JSON file that you can then upload to your own AI for analysis. You will find that script at:

https://github.com/directorcia/Office365/blob/master/Analysis/Secure%20Score/o365-secure-score-extract.ps1

and the documentation is here:

https://github.com/directorcia/Office365/wiki/Extract-Microsoft-365-Secure-Score-information

To use this script you need to have the PowerShell Graph module installed and use an account that has appropriate access to M365 security information.

Screenshot 2026-01-23 074402

When run, you’ll see it extract the security from various places in the tenant as shown above.

Screenshot 2026-01-23 074545

It will then save that information to a local file as shown above.

Screenshot 2026-01-23 074702

In this case you’ll see that I used the –compact option to two data files. The normal one, which is around 8MB and a smaller one around 234KB. The reason for this is that I found in my testing that many AI systems don’t support large file uploads (M365 Copilot does but). So the smaller one can work with those limited systems.

Once you give your AI system of choice access to the data file by uploading it, you can then use any prompt you wish to analyse the data. Here are some prompts I have created you can use. A long one:

https://github.com/directorcia/Office365/blob/master/Analysis/Secure%20Score/prompt-long.txt

and a shorter one:

https://github.com/directorcia/Office365/blob/master/Analysis/Secure%20Score/prompt-short.txt

I have uploaded my test data into a variety of AI systems but have gotten the best results from M365 Copilot Researcher and Analyst:

Screenshot 2026-01-23 075229

Screenshot 2026-01-23 080158

My original script does the extraction and the uploading for you together, but this new script now allows you to do just the extraction and then take that data and use any AI system or prompt you wish.

I have also created a number of additional scripts that extract as well as analyse a variety of other M365 services such as Exchange, SharePoint Entra Id and more. These are available to CIAOPS Patrons.

If you find a great prompt to use with this extracted data, let me know and I’ll share it so everyone can benefit.

Combining PowerShell and AI for M365 Security Analysis

powershell_ai_m365_security_no_text

I’ve used AI to create smart Microsoft 365 expert technical agents which I have deployed to Teams for CIAOPS Patrons:

image

I’ve also created a smart Microsoft 365 expert technical agent that you can use for free via email:

https://blog.ciaops.com/2025/06/11/get-your-m365-questions-answered-via-email-2/

simply by putting your question in the body of an email and sending it to robert.agent@ciaops365.com.

Now, I have integrated AI into my PowerShell scripts! Let me explain what I’ve done.

I’ve created an agent in Azure AI Foundry that is ‘grounded’ with all my M365 knowledge that is in the CIAOPS Patron community. I’ll cover off what I have learned about Azure AI Foundry in another post.

Next, I created a PowerShell script that firstly logs into a tenant to be inspected,

image

extracts all the security information like Secure Score details, Conditional Access policies and more,

image

bundles all that up into a single JSON file (about 8MB in size)

image

and then connects to my Foundry agent and uploads that extracted data for analysis

image

After analysis it generates and displays an extensive HTML report

image

which looks like:

image

and you can find a complete copy of to review at here, because it is too large for this post:

https://github.com/directorcia/Office365/blob/master/Analysis/secure-score-foundry.png

image

I’ve configured my Foundry agent to use a ‘Model router’, meaning that the agent uses what it things is the best LLM to do the analysis automatically.

The report include Prioritized recommendations:

image

A visualized Remediation Roadmap:

image

and whole lot more. I encourage you to take a moment and study the example output for yourself, which is AI generated.

I am now building similar AI analysis scripts for al M365 services like Exchange, SharePoint, etc and plant expand these over time.

Here’s the best part. As part of my testing process I am happy to make this Secure Score AI Analysis script available to a select few who read this and send me an email (director@ciaops.com) asking for a copy. You’ll need to be comfortable with PowerShell and have the MSGraph module already installed to run the script. Even better for the select few that do respond – I’ll give you access to my Azure AI Foundry agent for FREE to do the analysis. There are some conditions you’ll need to agree to, like going on my email list and understanding this is all still a beta test but there will be no cost if you qualify and agree. To start that process just email me (director@ciaops.com) saying you are keen to give it a go and I’ll send along the all the details.

There are just so many ways that I can see how to integrate AI with PowerShell and I’ll be sharing more soon on what I am doing.