- It is essential to prepare the environment (Windows versions, PowerShell, .NET and execution policies) and assign appropriate roles in Microsoft 365 before using PowerShell.
- Modern modules (ExchangeOnlineManagement, Microsoft.Graph, SharePoint Online, and MicrosoftTeams) allow you to connect to multiple services in a single session with modern authentication and MFA.
- The correct use of certificates, Managed Identities and explicit session closure improves security, avoids session limits and facilitates unattended automation.
- Most connection errors are resolved by checking installed modules, RBAC permissions, TLS compatibility, and proxy or firewall settings.

If you manage Microsoft 365/Office 365 on a daily basis, sooner or later you'll discover that doing it only from the admin center is a bottleneck. PowerShell becomes the Swiss Army knife to manage mailboxes, users, SharePoint sites, Teams, or security policies in a massive and automated way.
The problem is that many admins end up with four or five PowerShell windows open at the same time: one for Exchange Online, one for SharePoint Online, one for Teams, one for Microsoft Graph… and so on. That approach is awkward, difficult to maintain, and inefficientIn this guide you will see how to prepare the environment and how to connect to run multiple Office 365 services from one or a few PowerShell sessionsusing modern modules and best security practices.
Prerequisites and environment preparation
Before you start typing commands like there's no tomorrow, it's a good idea to make sure that the position you're managing from meets certain requirements. minimum system, network and security requirementsIf you skip this part, you'll end up with cryptic errors like "cmdlet not recognized", "cannot load file", or authentication problems.
Regarding the operating systemYou need a 64-bit version of Windows. Supported operating systems include, but are not limited to:
- Windows 11 and Windows 10
- Windows 8/8.1 and Windows 7 SP1
- Windows Server 2012, 2012 R2, 2016, 2019 and 2022
On these devices, the recommended version is PowerShell 5.1 or PowerShell 7+If you are using Windows PowerShell 5.1, make sure you have .NET Framework 4.7.2 or higher installed and the PowerShellGet module updated, as this is what allows Install modern modules from PowerShell Gallery with very comfortable Install-Module.
At the network level, You must have HTTPS access (TCP 443) towards Microsoft 365 domains, such as:
- outlook.office365.com (Exchange Online)
- login.microsoftonline.com (authentication)
- graph.microsoft.com (Microsoft Graph)
- *.office365.com, *.microsoft.com in more restricted scenarios
If you are in an environment with a corporate firewall or proxy, check with the networking team that these endpoints are not being filtered. A simple Test-NetConnection outlook.office365.com -Port 443 It helps you verify basic connectivity.
Another pillar is the script execution policyMany modules load local or remote scripts, and if the policy is too restrictive, they will be blocked.
Get-ExecutionPolicyto see the current value.- RemoteSigned This is the most common balance point: it allows unsigned local scripts and requires signatures for scripts downloaded from the Internet.
To set it only for the current user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
In some environments, it is preferred AllSigned (all signed) or, in very specific cases of evidence, Unrestricted o Bypass at the process level. The key is for you to understand that, without adjusting this, You will not be able to import sessions or run connection scripts.
Administrator role and required permissions
No matter how well set up your environment is, if the account you're connecting with doesn't have permissions, You're going to get "Access denied" errors one after another.To manage Microsoft 365 globally with PowerShell, you need at least one of these roles:
- Global Administrator, if you want to control practically everything.
- Exchange Administrator for the mail and mailboxes section.
- Other specific roles: Security Administrator, Teams Administrator, etc.
Exchange Online uses RBAC, so your account must be in groups like Organization Management o Recipient Management to be able to create and modify mailboxes, rules, etc. And if you're going to use Microsoft Graph, You will need to consent to the appropriate scopes, For example:
- User.Read.All to enumerate users and read basic data.
- Group.ReadWrite.All to manage groups and, among other things, Teams.
Also keep in mind that you can Enable or disable access to Exchange Online PowerShell per user with cmdlets like:
Set-User -Identity [email protected] -EXOModuleEnabled $trueSet-User -Identity [email protected] -EXOModuleEnabled $false
This is very useful for hardening the attack surface: Not everyone needs to be able to open an Exchange Online PowerShell sessioneven if it has a mailbox.
Installing key modules for Office 365/Microsoft 365
To connect to the various services in a modern way, you no longer need those old MSI installers for "Microsoft Online Services Sign-In", Lync Online, etc. Most current modules are installed directly from the PowerShell Gallerywhich greatly simplifies maintenance and updates.
The basic building blocks you should have installed are:
- Exchange Online Management: EXO V2 module for Exchange Online (main cmdlet:
Connect-ExchangeOnline). - Microsoft.Graph and optionally Microsoft.Graph.Beta- Official Microsoft Graph SDK for PowerShell.
- Microsoft.Online.SharePoint.PowerShellSharePoint Online administration.
- Microsoft TeamsMicrosoft Teams management via PowerShell.
Typical installation (running PowerShell as administrator):
Install-Module -Name ExchangeOnlineManagement -Force -AllowClobber
Install-Module -Name Microsoft.Graph -Scope CurrentUser
Install-Module -Name Microsoft.Online.SharePoint.PowerShell -Force
Install-Module -Name MicrosoftTeams -Force
The option -Strength It forces the installation or update, while -AllowClobber This allows you to override cmdlets from other modules if a conflict exists. After this, you can verify each module with:
Get-Module -ListAvailable -Name ExchangeOnlineManagement
If you need compatibility with older scripts, you can also keep classic modules like MSOnline o AzureADBut Microsoft's recommendation is to migrate towards Microsoft Graph PowerShellwhich is the future of identity and resource management.
Connect to multiple services in a single PowerShell session
The ideal goal is to work from a single console to avoid jumping between windows. The good news is that today it can be done perfectly well provided you load the appropriate modules and understand how each connection cmdlet works.
As a general pattern, you can follow this flow:
- Start PowerShell (preferably 64-bit, with elevated permissions if you are going to modify ExecutionPolicy).
- Create a credentials object, if the module accepts it (
Get-Credential). - Load the modules you are going to use with
Import-Module. - Run the connection cmdlets: Exchange, Graph, SharePoint, Teams…
Simple example of an interactive login for multiple services:
$credential = Get-Credential
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -ShowProgress:$true
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
$orgName = "tuempresa" # subdominio de tutenant.onmicrosoft.com
Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $credential
Import-Module MicrosoftTeams
Connect-MicrosoftTeams -Credential $credential
Meanwhile, for Microsoft Graph, authentication takes a different approach. You can't pass the credentials directly to the cmdletInstead, an interactive flow based on OAuth 2.0 is opened:
Connect-MgGraph -Scopes "User.Read.All","Group.ReadWrite.All"
A prompt will appear asking you to log in to your browser and grant permission for these scopes. Once accepted, the Graph session will be usable in the same PowerShell window that is already connected to Exchange, SharePoint, and Teams.
With this approach, you have everything you need centralized in a single session to manage accounts, mailboxes, sites, teams, and security settingswithout opening tabs like there's no tomorrow.
Using Microsoft Graph PowerShell organization-wide
Microsoft Graph PowerShell is the "new standard" for accessing the Microsoft 365 API layer. With a single SDK you can touch users, groups, Teams, devices, reports, etc. From PowerShell, the experience is similar to any other module, but with the nuance of scopes and the delegated vs. application-only model.
To work interactively, it is common to use delegated accessYou log in as a user (usually admin) and consent on behalf of that user:
Install-Module Microsoft.Graph -Scope CurrentUser
Import-Module Microsoft.Graph
Connect-MgGraph -Scopes "User.Read.All","Group.ReadWrite.All"
With those scopes you can, for example:
- List users to locate the ID of the logged-in user.
- See the teams he is part of (joinedTeams).
- List channels of a specific team.
- Send messages to a Teams channel from scripts.
For unattended scenarios (scheduled jobs, CI/CD pipelines, nightly automations…), the best option is to switch to application-only authentication with an app registration in Microsoft Entra ID and an X.509 certificate. In that case, the app authenticates with AppId, TenantId and certificateAnd you don't need human interaction, allowing you to run background tasks in a controlled manner.
Modern connectivity to Exchange Online and other environments
For years I connected to Exchange Online with New-PSSession and basic authentication. That route has been officially closed since October 2022Now everything goes through the ExchangeOnlineManagement module, which uses modern authentication (OAuth 2.0) and supports MFA, certificates, Managed Identities, etc.
The basic pattern for human admins is:
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName [email protected]
The login window opens, you enter your password, resolve the MFA, and you're done. From there you can use cmdlets like Get-EXOMailbox, Get-EXOMailboxStatistics, New-Mailbox, Set-Mailbox o Remove-Mailbox no more.
To automate without a browser, you have several options. certificate-based authentication o Managed Identities in Azure:
Connect-ExchangeOnline -ManagedIdentity -Organization tudominio.onmicrosoft.com
Alternatively, using a registered app and a certificate:
Connect-ExchangeOnline -AppId "APP-ID" -Organization "tudominio.onmicrosoft.com" -CertificateThumbprint "THUMBPRINT"
This type of connection is ideal when you want to run recurring scripts from Azure Automation, Azure Functions, or a managed identity VM: There are no plaintext passwords and the certificate lifecycle is well controlled.
Connect to SharePoint Online and Teams from PowerShell
Once you have email and identity covered, you'll likely want to orchestrate SharePoint sites and Teams teams from scripts. The process is very similar to what you've seen with Exchange; only the modules and cmdlets differ.
To SharePoint Online You need to know your tenant's administration URL, something like this: https://tuempresa-admin.sharepoint.comThe basic connection is:
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
$cred = Get-Credential
Connect-SPOService -Url "https://tuempresa-admin.sharepoint.com" -Credential $cred
From there you have cmdlets at your disposal such as Get-SPOSite to list site collections, commands to apply policies, manage storage, etc. You can reuse the same credentials object for other servicessimplifying the script.
In the case of Microsoft TeamsThe module also supports modern authentication and MFA. A typical workflow would be:
Import-Module MicrosoftTeams
Connect-MicrosoftTeams -Credential $cred
Alternatively, you can let it open the login dialog without passing explicit credentials. Once logged in, key cmdlets such as Get-Team, New-Team o Get-TeamUser They allow you to automate team creation, member management, channel configuration, etc., often in combination with Microsoft Graph for more advanced scenarios.
Secure session management and disconnection
PowerShell is not just plug and play: Open sessions also need to be managed properly.Exchange Online, for example, imposes a limit of about 3 concurrent sessions per user, and if you leave them open you will end up running into the famous "maximum number of sessions has been exceeded" error.
The recommended practice is explicitly close the sessions When you finish your tasks, instead of simply closing the window. For Exchange Online with EXO V2:
Disconnect-ExchangeOnline -Confirm:$false
If you have also generated remote sessions with New-PSSession for other services (or for compatibility with older scripts), it's also advisable to clean them up:
Get-PSSession | Remove-PSSession
SharePoint and Teams have their own disconnect cmdlets:
Disconnect-SPOService
Disconnect-MicrosoftTeams
Working this way avoids orphaned sessions on servers, frees up resources, and reduces security risks. Also, if you have long scripts, consider run them in a single session and monitor wait times instead of creating random, looping connections and disconnections.
Troubleshooting common connection problems
No matter how finely you have it set up, you're almost certain that at some point a strange message will appear. Most errors connecting to Office 365 services with PowerShell fall into a few typical groups:
When you see messages like “The term 'Connect-ExchangeOnline' is not recognized”, it usually means that The module is not installed or has not been imported correctlyYou can verify this with:
Get-Module -ListAvailable -Name ExchangeOnlineManagement
If it doesn't appear, reinstall it from the PowerShell Gallery. If it appears but doesn't load, Make sure you're not using an outdated or 32-bit version of PowerShell. that does not support that module.
Authentication errors (“Access denied”, “you do not have sufficient permissions”) are usually due to:
- Insufficient roles in Microsoft 365 (lack of Exchange Admin, Global Admin, etc.).
- Unmet MFA requirements, disabled app password, or conditional access policies.
- Corrupted searched credentials in the Windows credential manager.
The solution here is to review the roles in the admin portal, check if the organization has conditional access rules blocking PowerShell, and, if necessary, delete saved credentials and test the login flow again.
Problems with TLS or proxies are also common: messages like “The underlying connection was closed” or “Unable to connect to the remote server” indicate that TLS 1.2 is not being used or the firewall is blocking traffic. Make sure you:
- Have .NET updated (4.6.2 or higher).
- Force TLS 1.2 if necessary from PowerShell.
- Verify that the proxy allows traffic to Microsoft endpoints.
Finally, when you have several modules installed (MSOnline, AzureAD, ExchangeOnlineManagement, older versions of EXO, etc.), they may appear cmdlet conflicts or versions. In that case:
- List of modules with
Get-Module -ListAvailable. - Find out which module a cmdlet belongs to with
Get-Command NombreCmdlet. - Explicitly import the correct version with
Import-Module -RequiredVersion. - Uninstall old modules you no longer need with
Uninstall-Module.
With these guidelines, most issues are resolved without having to drive yourself crazy reading endless logs.
Mastering the connection to multiple Office 365 services using PowerShell allows you to move from making manual changes in the portal to Automate massive tasks, apply advanced configurations that don't even appear in the GUI, and maintain much finer control over security and access.Properly preparing the environment (versions, modules, permissions, and execution policies), using modern authentication with MFA and certificates, centralizing connections into one or a few sessions, and managing the session lifecycle will make your day-to-day work as a Microsoft 365 admin much smoother and, above all, scalable.
Passionate writer about the world of bytes and technology in general. I love sharing my knowledge through writing, and that's what I'll do on this blog, show you all the most interesting things about gadgets, software, hardware, tech trends, and more. My goal is to help you navigate the digital world in a simple and entertaining way.