A Cleaner Way to Connect PowerShell to Microsoft Teams

image

If you still rely on Connect-MicrosoftTeams with an interactive sign-in every time you need to do some administration, you already know the frustration.

Scripts stop and wait for credentials. Scheduled tasks simply can’t run unattended. MFA prompts interrupt automation. And if you’re managing multiple tenants as an MSP, jumping between browser windows and authentication prompts quickly becomes tedious.

Microsoft has supported certificate-based authentication for Teams PowerShell for some time. The challenge hasn’t been the technology. The challenge has been the setup.

I’ve created a script that handles that process for me, removing most of the manual work and making certificate-based authentication something I can deploy consistently across customer tenants. The approach follows the same design philosophy I’ve been using for Exchange Online and other Microsoft 365 workloads: automate the plumbing so I can focus on the outcome. You can find it here:

https://github.com/directorcia/Office365/blob/master/o365-connect-tms-cert.ps1

and the documentation is here:

https://github.com/directorcia/Office365/wiki/Certificate-based-connection-for-Teams

What the Script Actually Does

The script operates in two primary modes.

The first mode, -GenerateLocalCertificate, creates a self-signed certificate on the local machine and exports the information needed for authentication. If required, it can also provision the Entra ID application automatically. The local certificate becomes the device’s identity when connecting to Teams PowerShell.

The second mode, -UseCertificateAuth, performs the actual Teams connection using the existing certificate and application registration. No password. No browser pop-up. No MFA prompt in the middle of an automated process.

The really useful feature is combining certificate generation with application provisioning. In a single operation the script can:

  • Create the local certificate

  • Authenticate to Microsoft Graph using device code authentication

  • Create or reuse an Entra ID application registration

  • Upload the certificate to the application

  • Create the required service principal

  • Assign the necessary permissions

  • Store the configuration details for future use

Tasks that typically involve multiple portals, several copy-and-paste operations, and more than a few opportunities to make mistakes can be reduced to a single repeatable process.

Why Certificate Authentication Matters

The biggest advantage is that you’re no longer tying automation to an admin account.

Traditional approaches often depend on an account that someone logs into interactively. That works fine until MFA settings change, conditional access rules are updated, or the account password expires.

Certificate authentication shifts the trust model. Instead of trusting a username and password, Microsoft validates the certificate installed on the machine against the certificate registered in Entra ID. If they match, the connection succeeds. If they don’t, access is denied.

That makes the solution both more secure and more reliable.

For MSPs, it also provides a cleaner operational model. Each technician workstation can have its own certificate while sharing the same application registration inside the customer tenant. If a machine is retired or a staff member leaves, removing the associated certificate immediately blocks access from that device without affecting anyone else.

The MSP Advantage

This is where the approach starts to shine.

A common question is whether every machine requires a separate application registration. The answer is no.

The design I prefer is a single Teams application per tenant with multiple certificates attached to it. Each device gets its own unique certificate, but all of them authenticate through the same application registration. That keeps administration simple while still maintaining proper separation between devices.

When a new technician needs access:

  1. Run the provisioning process.

  2. Generate a new certificate.

  3. Associate it with the existing application.

  4. Start working.

When access needs to be removed:

  1. Delete the certificate association.

  2. Access from that machine immediately stops.

No password resets. No account changes. No disruption for other administrators.

Getting Started

If you’re still connecting to Teams PowerShell interactively for daily administration, I’d encourage you to investigate certificate-based authentication.

The technology isn’t new. What’s important is reducing the complexity required to deploy it.

The real benefit isn’t that you save a few clicks when connecting. The real benefit is that you create a repeatable, secure authentication framework that supports automation, improves operational consistency, and removes dependence on administrator credentials.

For MSPs managing multiple tenants, that’s a significant improvement.

The less time I spend authenticating, the more time I spend solving customer problems. And that, ultimately, is the point.

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.