Managing Exchange Online with PowerShell makes many day-to-day tasks much easier (and faster). You may need PowerShell not only for your daily tasks, but some settings in Exchange Online can only be changed using PowerShell. So how do you connect to Exchange Online with PowerShell?

The most recent version ofMódulo Powershell para Exchange Online, EXO V3,that we'll be using supports modern authentication and supports MFA. So you no longer need to create an app password. Also, the new engine is faster and more secure as compared to the old Exchange Online engine.
Requirements for EXO V3
The previous version of the Exchange Online PowerShell module (EXO v2) was only supported on Windows and required PowerShell 5.x. However, the EXO V3 module is fully compatible with PowerShell 7, macOS and Linux. So this is great news.
You must configure PowerShell to run remote scripts. By default this is disabled.
- Open PowerShell in elevated mode
Press Windows key + X and select Windows PowerShell (Admin) - Set the execution policyfor remote signing:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
You only need to set this once per computer. So whatSet execution policyand try to connect to Exchange Online, you will get an error:
Files cannot be uploaded because script execution is disabled on this system. Provide a valid certificate to use to sign the files.
Instale o módulo Exchange Online V3 no PowerShell
We need to install the EXO V3 module in PowerShell before we can connect to Exchange Online. Reopen an elevated Windows PowerShell window:
- Open PowerShell in elevated mode
Press Windows key + X and select Windows PowerShell (Admin) - Instalar o PowerShellObtener
We need to install PowerShellGet before we can install the EXO V3 module.
# Close the PowerShell window and reopen it when done Install-Module -Name PowerShellGet -Force
- Install the EXO V3 module
We can now install the latest Exchange Online PowerShell module using the Install-Module cmdlet
# Add -Force if you need to update EXO V1.Install-Module -Name ExchangeOnlineManagement -Force
Automatically check if the EXO module is installed
Will you be using the Exchange Online module in a script? Then automatically check if the module is installed before trying to connect.
With a single cmdlet we can list all modules installed in PowerShell. You can avoid unnecessary errors by simply checking whether the ExchangeOnlineManagement module is available.
(Get-Module -ListAvailable -Name ExchangeOnlineManagement) -ne $null
The above command should return a list of installed Exchange Online modules. If the result is empty, we know that the module is not installed.
Connect to Exchange Online with PowerShell
With the Exchange Online module installed, we can now easily connect to Exchange Online with a single cmd in PowerShell:
Connect-ExchangeOnline-UserPrincipalName[email protected]-showProgress $true
The new EXO V3 module also supports connecting to another tenant. If you are a Microsoft partner and need to connect to another tenant, you can connect by adding thedelegated organizationchange.
Connect-ExchangeOnline-UserPrincipalName[email protected]-ShowProgress $true -Delegated Organization contoso.onmicrosoft.com
Connect to Exchange Online feature for PowerShell
All functionality below can be used in scripts to connect to Exchange Online. This feature checks if the Exchange Online module is installed and when it offers the option to install it automatically.
It also validates existing Exchange Online connections in PowerShell, preventing multiple connections from the same session.
ConnectTo EXO Function { <# .SYNOPSIS Connects to EXO when not connected. Check EXO v3 module #> param([Parameter (Required = $true)] [string] $adminUPN) process { # Check if EXO is installed and connect if not connected if ($null - eq (Get-Module - ListAvailable) - Name ExchangeOnlineManagement)) { Write-Host "Exchange Online PowerShell v3 module is required, would you like to install it?" -ForegroundColor Yellow $install = Read-Host Do you want to install the module? [Y] Yes [N] No if($install -match "[yY]") { Write-Host "Install Exchange Online PowerShell v3 Module" -ForegroundColor Cyan Install-Module ExchangeOnlineManagement -Repository PSGallery -AllowClobber -Force }else { Write "Install EXO v3 module" error. } } if ($null -ne (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) { # Check which version of Exchange Online is installed if (Get-Module -ListAvailable -Name ExchangeOnlineManagement | Where-Object {$_. version -like "3.*"} ) { # Check for active EXO sessions if ((Get-ConnectionInformation).tokenStatus -ne 'Active') { write-host 'Connecting to Exchange Online' -ForegroundColor Cyan Connect-ExchangeOnline - UserPrincipalName $adminUPN } }else{ # Check for active EXO sessions $psSessions = Get-PSSession | Select-Object -Property State, Name If (((@($psSessions) -like '@{State=Opened; Name=ExchangeOnlineInternalSession*').Count -gt 0) -ne $true) {write-host 'Connecting- se a Exchange Online' -ForegroundColor Cyan Connect-ExchangeOnline -UserPrincipalName $adminUPN } } }else{ Misspelling "Install EXO v3 module". 🇧🇷
Sign in to Exchange Online as a delegated (partner) administrator.
If you manage multiple tenants, you might also need to connect to Exchange Online. Instead of using a dedicated customer tenant admin login, you can also log in to Exchange Online as a delegated admin.
This allows you to use your own credentials to authenticate. To do this, you must use the parameter-Delegated organization
.
# Replace stonegrovebank.onmicrosoft.com with the organization you want to manage. Connect-ExchangeOnline -DelegatedOrganization stonegrovebank.onmicrosoft.com# You can also optionally provide your usernameConnect-ExchangeOnline -UserPrincipalName[email protected]- Delegated organization stonegrovebank.onmicrosoft.com
You can now manage all mailboxes in the associated tenant.
Connecting to Exchange Online PowerShell without Modern Authentication
You can use the following method to connect to Exchange Online in PowerShell if your account doesn't already support modern authentication:
$cred = Get-CredentialConnect-ExchangeOnline -Credential $cred -ShowProgress $true
Make sure Exchange Online is connected
When using the Exchange Online module in scripts, it's a good idea to check that you're already signed in. Note that you can only have 5 concurrent connections to Exchange Online. And you probably don't want to apply if you don't have to.
We can use the cmdletget connection information
since EXO v3. If you are using an older version of Exchange Online, you should useObter PSSession
.


You can use the following snippet to verify that you have an active ExchangeOnline session for V3 and earlier. First we check that the ExchangeOnline module is installed and then that version 3.x is not installed. Then we check the existing connections depending on the version.
if ($null -ne (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) { # Comprovar qual versão do Exchange Online está instalada if (Get-Module -ListAvailable -Name ExchangeOnlineManagement | Where-Object {$_.version -like "3 .*"} ) { # Verifique se há sessões EXO ativadas if ((Get-ConnectionInformation).tokenStatus -ne 'Active') { write-host 'Connecting to Exchange Online' -ForegroundColor Cyan Connect-ExchangeOnline -UserPrincipalName $adminUPN } } else{ # Komprobation, wenn EXO-Sitzungen ativiert sind $psSessions = Get-PSSession | Select-Object -Property State, Name If (((@($psSessions) -like '@{State=Opened; Name=ExchangeOnlineInternalSession*').Count -gt 0) -ne $true) {write-host 'Conectando-se a Exchange Online' -ForegroundColor Cyan Connect-ExchangeOnline -UserPrincipalName $adminUPN } } }
Retrieve mailbox information
With the new EXO V3 module, now you can easily get mailbox details with the following shortcut:
# Alternate form: Get-ExoMailbox -identity[email protected]# With EXO V2 module, you can write the following shortcut Get-ExoMailbox johndoe
separate your sessions
Always make sure to sign out of your Exchange Online session before closing the PowerShell window. If you don't log out, you may be using all 5 remote PowerShell connections to Exchange Online. In that case, you must wait for the sessions to expire before reconnecting.
Disconnect-ExchangeOnline
PowerShell Connection to Exchange Online Alternative
If you cannot use the new EXO v2 module, for example because you are using basic authentication, you can still connect to Exchange Online. Note that this will eventually become deprecated. Therefore, use the modern authentication option described above whenever possible.
For the basic authentication method, we'll import the Exchange Online cmdlets. First, make sure you've set the execution policy for remote signing:
- Open PowerShell in elevated mode
Press Windows key + X and select Windows PowerShell (Admin) - Set the execution policyfor remote signing:
Set-ExecutionPolicy RemoteSigned
- To connect to Exchange Online, we first need to save our credentials:
$cred = get-credential
- Next, we can create and import the Exchange Online cmdlet in PowerShell:
# Create session $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection# Import into your PowerShell sessionImport-PSSession $Session - Desativar verificação de nome
Be sure to disconnect your session when you're done:
Remove-PSSession $Session
common questions
Error: Files cannot be loaded because scripts are running...
When you get the error"The files cannot be uploaded because script execution is disabled on this system. Please provide a valid certificate that can be used to sign the files."so you forgot to set the execution policy.
Run the following command in an elevated PowerShell window:Set-ExecutionPolicy RemoteSigned
Unable to validate argument in parameter 'session' - error
You're trying to connect to Exchange Online with an MFA-enabled account while using the basic authentication option.
Make sure to install the latest Exchange Online engine, EXO V3, as explained at the beginning of the article.
Unable to create a runspace because the maximum number of connections allowed was exceeded
You have used all 5 available connections to Exchange Online. Be sure to disconnect your PowerShell sessions.
To close current sessions, you can run the following command:
Get PSSession | Delete PSSession
Connection to the remote Outlook.Office365.com server failed with the following error
Error Message: Access Denied
To connect to Exchange Online, you must use an account that is a global administrator in Office 365. The account you are connecting with does not have the correct permissions.
Fim
The new Exchange Online engine is really powerful and makes working with Exchange Online much easier. I hope this article helped you get started. If you have any questions, just leave a comment below.
You may also be interested in the following articles:
- Enable Office 365 Plus addressing
- Find all email addresses with PowerShell
- Connect PowerShell to Office 365
0Share
FAQs
How do I connect to ExchangeOnline PowerShell V2? ›
Connect to Exchange Online PowerShell V2
Connect with your admin account to Exchange Online. Run the Connect-ExchangeOnline cmdlet. In the sign-in window that opens, enter your password, and then click Sign in.
Open an elevated Windows PowerShell command prompt (run Windows PowerShell as an administrator). Run the Install-Module MSOnline command. If you're prompted to install the NuGet provider, type Y and press Enter. If you're prompted to install the module from PSGallery, type Y and press Enter.
How do I access ExchangeOnline MFA with PowerShell? ›To connect to Exchange Online PowerShell with MFA, you need to install the Exchange Online PowerShell V2 module. With this module, you can create a PowerShell session with both MFA and non-MFA accounts using the Connect-ExchangeOnline cmdlet.
How to install and connect to ExchangeOnline PowerShell module? ›- Install or update the PowerShellGet module as described in Installing PowerShellGet.
- Close and re-open the Windows PowerShell window.
- Now you can use the Install-Module cmdlet to install the module from the PowerShell Gallery.
You get Exchange Online when you sign up for Microsoft 365 for business and Microsoft 365 for enterprise subscriptions. You can also buy standalone Exchange Online plans (https://www.microsoft.com/en-us/microsoft-365/exchange/compare-microsoft-exchange-online-plans) for your organization.
How do I run a PowerShell command in exchange? ›- Open PowerShell and enter the following command: $LiveCred = Get-Credential.
- Enter the login credentials for Exchange when the window appears, and then click "OK."
- Enter the following command once the previous command has processed: Remove-PSSession $Session.
- Open a PowerShell session.
- Store your Credentials in a variable: $Cred = Get-Credential.
- Enter your Office 365 Credentials when prompted:
- Import the session: Import-PSSession $Session. ...
- Now you can run any commands you need.
Exchange Online PowerShell is the administrative interface that enables you to manage your Microsoft Exchange Online organization from the command line. For example, you can use Exchange Online PowerShell to configure mail flow rules (also known as transport rules) and connectors.
What does F7 do in PowerShell? ›If you have been entering several commands in a console screen, pressing the F7 function key displays a menu of the previously executed commands, as Figure 2.2 shows. Figure 2.2. Pressing the F7 function key presents a command history menu.
How to connect to Exchange Online without Basic authentication? ›For Exchange Online PowerShell
While EXO V2 uses modern authentication, WinRM basic authentication is necessary to transport modern authentication tokens. So, to overcome this issue, you can use the EXO V2 Module Preview, which lets admins connect to Exchange Online without enabling WinRM basic authentication.
How do I link my office 365 MFA to PowerShell? ›
- To do so, run the Windows PowerShell console as administrator.
- Enter the following PowerShell commands: Import-Module MsOnline. Connect-MsolService.
- A Microsoft 365 prompt windows opens where you enter your M365 admin credentials.
Enabled: The user has been enrolled in MFA but has not completed the registration process. They will be prompted to complete the registration process the next time they sign in. Enforced: The user has been enrolled and has completed the MFA registration process.
What are the different methods to install PowerShell? ›- Install PowerShell using Winget (recommended)
- Installing the MSI package.
- Installing the ZIP package.
- Install as a .NET Global tool.
- Installing from the Microsoft Store.
- Installing a preview version.
- Upgrading an existing installation.
- Deploying on Windows 10 IoT Enterprise.
- On the Hyper-V host, open Windows PowerShell as Administrator.
- Use the Enter-PSSession cmdlet to connect to the virtual machine. ...
- Type your credentials for the virtual machine.
- Run whatever commands you need to.
- Unblock the Internet-downloaded NuGet package ( . nupkg ) file, for example using Unblock-File -Path C:\Downloads\package. ...
- Extract the contents of the NuGet package.
- The . PS1 file in the folder can be used directly from this location.
- You may delete the NuGet-specific elements in the folder.
OWA-only mailbox has all the same functionality as an Exchange mailbox besides desktop client availability, making it accessible only via Outlook Web Access. Note: you can connect your Outlook client to an OWA-only mailbox using IMAP/SMTP or POP/SMTP protocols or EWS.
Is Microsoft Exchange the same as Exchange Online? ›Microsoft Exchange Server is built on dedicated physical or virtual servers which require a lot of maintenance, while Microsoft Exchange Online is completely cloud-based. Microsoft Exchange Server needs both server licenses as well as client access licenses for employees to use the system.
What is the best website to go to when you want to access your Office 365 account? ›Signing in at Office.com or signing in to the Office desktop apps also means you can easily access any files you stored in cloud services such as OneDrive. Learn more at Sign in to Office or Microsoft 365.
What does F8 do in PowerShell? ›...
Keyboard shortcuts for running scripts.
Action | Keyboard Shortcut |
---|---|
Open | CTRL + O |
Run | F5 |
Run Selection | F8 |
Stop Execution | CTRL + BREAK . CTRL + C can be used when the context is unambiguous (when there is no text selected). |
Array subexpression operator @( )
Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. PowerShell Copy.
Can I run SFC from PowerShell? ›
NOTE: System File Checker can be run from Windows PowerShell (Admin). On the User Account Control (UAC) prompt, click Yes. In the command prompt window, type SFC /scannow and press Enter . System file checker utility checks the integrity of Windows system files and repairs them if required.
Can PowerShell interact with Outlook? ›PowerShell uses . NET to control Outlook programmatically, file away the reports, and create customized emails for each recipient. This technique could easily be modified to perform other types of email processing or to automate other Office products.
How to configure Outlook using PowerShell? ›Configure the PowerShell connection
Instance type: Select PowerShell Exchange/Office 365. Instance name: A name to identify the instance. Exchange server: For Exchange Server, enter the name or IP address of your server. For Exchange Online, enter outlook.office365.com if you're using the global Office 365 service.
You need to open the URL in a browser on any computer, and then enter the unique code. After you complete the login in the web browser, the session in the Powershell 7 window is authenticated via the regular Azure AD authentication flow, and the Exchange Online cmdlets are imported after few seconds.
What can be used to manage Exchange servers using PowerShell? ›The Exchange Management Shell is built on Windows PowerShell technology and provides a powerful command-line interface that enables the automation of Exchange administration tasks. You can use the Exchange Management Shell to manage every aspect of Exchange.
How do I automate an Exchange PowerShell script? ›- Generate a certificate to use for authentication.
- Set up an Application Registration.
- Assign API permissions to the Application (and grant admin consent).
- Assign certificate-based credentials to the Application Registration.
@{} in PowerShell defines a hashtable, a data structure for mapping unique keys to values (in other languages this data structure is called "dictionary" or "associative array"). @{} on its own defines an empty hashtable, that can then be filled with values, e.g. like this: $h = @{} $h['a'] = 'foo' $h['b'] = 'bar'
What is F12 used for? ›Enhanced function key | What it does |
---|---|
Open | F5: Opens a document in programs that support this command. |
F12: Prints the file in the active window. | |
Redo | F3: Cancels the previous undo action. |
Reply | F7: Replies to the e-mail in the active window. |
The function keys or F keys are lined across the top of the keyboard and labeled F1 through F12. These keys act as shortcuts, performing certain functions, like saving files, printing data, or refreshing a page. For example, the F1 key is often used as the default help key in many programs.
How to connect to Exchange Online PowerShell without Basic authentication? ›Connect-ExchangeOnline cmdlet allows you to connect Exchange Online PowerShell without Basic Authentication. This cmdlet only available in EXO V2 module. You can use Connect-ExchangeOnline cmdlet for both MFA and non-MFA account to connect Exchange Online PowerShell. It will prompt for username and password.
Does Exchange Online require TLS? ›
Exchange Online servers always encrypt connections to other Exchange Online servers in our data centers with TLS 1.2. When you send a message to a recipient that is within your organization, Exchange Online automatically sends the message over an encrypted connection using TLS.
How do I enable basic authentication in Office 365 PowerShell? ›- To allow Basic authentication for the protocol, use this switch without a value.
- To block Basic authentication for the protocol, use this exact syntax: -AllowBasicAuthPowershell:$false .
- Step 1: Load the Exchange Online PowerShell module. Note. ...
- Step 2: Connect and authenticate. ...
- Step 3: Disconnect when you're finished.
The most secure form of MFA is the security key. The security key, being a separate device altogether, won't leave your accounts unprotected in the event of a mobile phone being lost or stolen. Both the SMS-based and app-based versions would leave your accounts at risk in this scenario.
Can hackers bypass MFA? ›Another social engineering technique that is becoming popular is known as “consent phishing”. This is where hackers present what looks like a legitimate OAuth login page to the user. The hacker will request the level of access they need, and if access is granted, they can bypass MFA verification.
Which is better 2FA or MFA? ›So, is MFA more secure than 2FA? The short bittersweet answer is, it depends. In general, any 2FA or MFA is more secure than single-factor authentication. However, the security added by any MFA strategy is as strong as the authentication methods chosen by risk professionals.
What are the 3 installation types? ›- Custom installation. A custom installation allows the installer to choose to select components or parts that are required to be installed. ...
- Silent installation. A "silent installation" is an installation that does not display messages or windows during its progress. ...
- Headless installation. ...
- Clean installation.
To sign in interactively, use the Connect-AzAccount cmdlet. This cmdlet presents an interactive browser based login prompt by default.
Which virtual machines can you manage by using PowerShell direct? ›You can use PowerShell Direct to run arbitrary PowerShell in a Windows 10 or Windows Server 2016 virtual machine from your Hyper-V host regardless of network configuration or remote management settings.
How do I join a VM to a domain in PowerShell? ›In the PowerShell console, run the Add-Computer cmdlet. This cmdlet performs the same action as adding a computer to a domain via the GUI. Specify the domain name to add the computer to with the DomainName parameter and optionally specify the Restart parameter to restart the computer when complete automatically.
How to install Nupkg PowerShell manually? ›
- Unblock the Internet-downloaded NuGet package ( . ...
- Extract the contents of the NuGet package to a local folder.
- Delete the NuGet-specific elements from the folder.
- Rename the folder. ...
- Copy the folder to one of the folders in the $env:PSModulePath value .
Put simply, a NuGet package is a single ZIP file with the . nupkg extension that contains compiled code (DLLs), other files related to that code, and a descriptive manifest that includes information like the package's version number.
Can PowerShell run bat scripts? ›Bat or. Cmd extension. Although PowerShell and Batch are different languages, both can be integrated into each other and helps to call and execute each other tasks. To call the PowerShell script from the Batch file we can use the below syntax in the Batch file.
How do I know if PowerShell v2 is installed? ›- Key Location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine.
- Value Name: PowerShellVersion.
- Value Type: REG_SZ.
- Value Data: <1.0 | 2.0>
- In Server Manager, from the Manage menu, select Add Roles and Features. ...
- On the Installation Type page, select Role-based or feature-based installation.
- On the Features page, expand the Windows PowerShell (Installed) node and select Windows PowerShell 2.0 Engine.
- On the Hyper-V host, open Windows PowerShell as Administrator.
- Use the Enter-PSSession cmdlet to connect to the virtual machine. ...
- Type your credentials for the virtual machine.
- Run whatever commands you need to.
Right click Windows PowerShell, and hit Run as Administrator to make sure that you can run PowerShell commands without restrictions.
Is PowerShell outdated? ›We recently announced that Windows PowerShell 2.0 is being deprecated in the Windows 10 Fall Creators Update.
Which of the following is a best practice for working with PowerShell? ›Avoid partial and positional parameter names in scripts
A syntax written with these parameter names is challenging to read. The situation is worse if there are too many parameters.
PowerShell Support Lifecycle - PowerShell | Microsoft Learn. This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
What does @{} mean in PowerShell? ›
To create an array, we create a variable and assign the array. Arrays are noted by the "@" symbol.
What is Microsoft Exchange Online PowerShell module? ›Exchange Online PowerShell is the administrative interface that enables you to manage your Microsoft Exchange Online organization from the command line. For example, you can use Exchange Online PowerShell to configure mail flow rules (also known as transport rules) and connectors.
What are the different types of PowerShell? ›- Type float uses the 32-bit IEEE single-precision representation.
- Type double uses the 64-bit IEEE double-precision representation.
In the Azure portal, navigate to the virtual machine resource. Navigate to Operations > Run Command. Select RunPowerShellScript from the list of commands. Type the PowerShell script content you want to run on the server in the Run Command Script pane.
How do I connect to a virtual machine using command prompt? ›- Locate the address of the SSH service. Port opening type. ...
- Use the address in a terminal emulation client (such as Putty) or use the following command line to access the VM directly from your desktop SSH client:
- ssh -p <port> user@<ip-address-or-hostname>
- Type Start PowerShell in the Command Prompt window to start Windows PowerShell.
- Type Install-WindowsFeature RSAT and press Enter to install RSAT.
A PowerShell graphical user interface (GUI) can help lower-XP PowerShell users to interact more safely and confidently with PowerShell. GUIs are great, because they: let users run PowerShell by themselves.