### Install or Update Module Examples Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Specific commands for installing or updating the module with different scopes and version requirements. ```PowerShell Install-Module -Name ExchangeOnlineManagement ``` ```PowerShell Update-Module -Name ExchangeOnlineManagement -Scope CurrentUser ``` ```PowerShell Install-Module -Name ExchangeOnlineManagement -AllowPrerelease ``` -------------------------------- ### OPATH Filter Enclosure Examples Source: https://learn.microsoft.com/en-us/powershell/exchange/recipient-filters Examples demonstrating how to wrap entire OPATH filters based on the contained value types. ```powershell "Name -eq '$User'" ``` ```powershell "CountryCode -eq '840'" ``` ```powershell {CountryCode -eq "840"} ``` ```powershell 'HiddenFromAddressListsEnabled -eq $true' ``` ```powershell "HiddenFromAddressListsEnabled -eq `$true" ``` -------------------------------- ### Check Installed Module Details Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Verify if the module is installed and determine its installation path. ```PowerShell Get-InstalledModule ExchangeOnlineManagement | Format-List Name,Version,InstalledLocation ``` -------------------------------- ### Module Installation and Update Syntax Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 General syntax for installing or updating the module using PowerShell Gallery cmdlets. ```PowerShell -Name ExchangeOnlineManagement [-Scope CurrentUser] [-RequiredVersion ] [-AllowPrerelease] ``` -------------------------------- ### OPATH Value Syntax Examples Source: https://learn.microsoft.com/en-us/powershell/exchange/recipient-filters Examples of how to format different data types within OPATH filters. ```powershell 'Value' ``` ```powershell 'Value with spaces' ``` ```powershell '$User' ``` ```powershell '$($User -Replace "'","''")' ``` ```powershell 500 ``` ```powershell $true ``` ```powershell $false ``` ```powershell $null ``` ```powershell `$true ``` -------------------------------- ### New-SystemMessage Parameter Sets Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-cmdlet-syntax Example syntax showing two distinct parameter sets for the New-SystemMessage cmdlet. ```powershell New-SystemMessage -DsnCode -Internal -Language -Text [-Confirm] [-DomainController ] [-WhatIf] ``` ```powershell New-SystemMessage -QuotaMessageType -Language -Text [-Confirm] [-DomainController ] [-WhatIf] ``` -------------------------------- ### Create Parallel Exchange Online Connections in C# Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exo-powershell-c-sharp This example shows how to initialize a RunspacePool, connect to Exchange Online across multiple runspaces, and execute cmdlets in parallel. ```csharp PowerShell CreateConnectionCommand(RunspacePool pool) { PowerShell ps = PowerShell.Create(); ps.RunspacePool = pool; ps.AddCommand("Connect-ExchangeOnline"); ps.AddParameters(new Dictionary { ["Organization"] = "contoso.onmicrosoft.com", ["CertificateFilePath"] = "C:\\Users\\Certificates\\mycert.pfx", ["CertificatePassword"] = GetPassword(), ["AppID"] = "a37927a4-1a1a-4162-aa29-e346d5324590" }); return ps; } void ParallelConnectionsToExchangeOnline() { // Setup the Initial Session State of each runspace in the pool // Import the ExchangeOnlineManagement module. // Set the Execution Policy of the runspace. InitialSessionState iss = InitialSessionState.CreateDefault(); iss.ImportPSModule(new string[] { "ExchangeOnlineManagement" }); iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned; iss.ThrowOnRunspaceOpenError = true; // Create a RunspacePool initialized with the Initial Session State. using (RunspacePool pool = RunspaceFactory.CreateRunspacePool(iss)) { // Configure the number of runspaces to maintain in the RunspacePool. pool.SetMaxRunspaces(3); pool.SetMinRunspaces(3); // Set the ThreadOptions to reuse the same threads for the runspaces so that // the Exchange Online cmdlets are available after running Connect-ExchangeOnline in each runspace. pool.ThreadOptions = PSThreadOptions.ReuseThread; pool.Open(); // Run the Connect-ExchangeOnline cmdlet in all the runspaces in the pool // so that any cmdlets can be run in them after that. PowerShell ps1 = CreateConnectionCommand(pool); PowerShell ps2 = CreateConnectionCommand(pool); PowerShell ps3 = CreateConnectionCommand(pool); // Execute each of the 3 Connect-ExchangeOnline commands asynchronously. IAsyncResult job1 = ps1.BeginInvoke(); IAsyncResult job2 = ps2.BeginInvoke(); IAsyncResult job3 = ps3.BeginInvoke(); // Get the results of the commands. PSDataCollection connectionResult = ps1.EndInvoke(job1); PSDataCollection connectionResult2 = ps2.EndInvoke(job2); PSDataCollection connectionResult3 = ps3.EndInvoke(job3); // Execute two Exchange-Online commands in parallel using the runspacepool. // All of them have an active connection to Exchange Online. // NOTE : Cmdlets that update the same object or can cause conflicting // results should not be run in parallel as they can lead to an undefined // outcome. PowerShell commandPS1 = PowerShell.Create(); commandPS1.RunspacePool = pool; commandPS1.AddCommand("Get-Mailbox"); commandPS1.AddParameter("Identity", "ContosoUser1"); PowerShell commandPS2 = PowerShell.Create(); commandPS2.RunspacePool = pool; commandPS2.AddCommand("Get-Mailbox"); commandPS2.AddParameter("Identity", "ContosoUser2"); IAsyncResult commandJob1 = commandPS1.BeginInvoke(); IAsyncResult commandJob2 = commandPS2.BeginInvoke(); // Wait for the commands to finish and return the results. PSDataCollection command1Result = commandPS1.EndInvoke(commandJob1); PSDataCollection command2Result = commandPS2.EndInvoke(commandJob2); // Check if there were any errors. if (!commandPS1.HadErrors) { // Write the results to console. foreach (PSObject result in command1Result) { Console.WriteLine(result.ToString()); } } else { // Write the errors to console by accessing the error stream of the Powershell object. foreach (ErrorRecord error in commandPS1.Streams.Error) { Console.WriteLine(error.ToString()); } } // Check if there were any errors. if (!commandPS2.HadErrors) { // Write the results to console. foreach (PSObject result in command2Result) { Console.WriteLine(result.ToString()); } } else { // Write the errors to console by accessing the error stream of the Powershell object. foreach (ErrorRecord error in commandPS2.Streams.Error) { Console.WriteLine(error.ToString()); } } } } ``` -------------------------------- ### Verify Installed Module Versions Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Checks for installed versions of PackageManagement and PowerShellGet to troubleshoot potential connection issues caused by preview versions. ```PowerShell Get-InstalledModule PackageManagement -AllVersions; Get-InstalledModule PowerShellGet -AllVersions ``` -------------------------------- ### Connect using a certificate object Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Allows using a certificate object without requiring local installation. ```PowerShell Connect-ExchangeOnline -Certificate <%X509Certificate2 Object%> -AppID "36ee4c6c-0812-40a2-b820-b22ebd02bce3" -Organization "contosoelectronics.onmicrosoft.com" ``` ```PowerShell Connect-IPPSSession -Certificate <%X509Certificate2 Object%> -AppID "36ee4c6c-0812-40a2-b820-b22ebd02bce3" -Organization "contosoelectronics.onmicrosoft.com" ``` -------------------------------- ### Execute Exchange Online Cmdlets in Azure Automation Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Example of connecting and running a basic command within an Azure Automation runbook. ```PowerShell Connect-ExchangeOnline -ManagedIdentity -Organization contoso.onmicrosoft.com ``` ```PowerShell Get-AcceptedDomain | Format-Table Name ``` -------------------------------- ### Create Automation Account with User-Assigned Managed Identity Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Syntax and example for creating an Automation account and assigning a user-managed identity. ```PowerShell $UAMI = (Get-AzUserAssignedIdentity -Name "" -ResourceGroupName "").Id New-AzAutomationAccount -Name "" -ResourceGroupName "" -Location "" -AssignUserIdentity $UAMI ``` ```PowerShell $UAMI = (Get-AzUserAssignedIdentity -Name "ContosoMI1" -ResourceGroupName "ContosoRG2").Id New-AzAutomationAccount -Name "ContosoAzAuto2" -ResourceGroupName "ContosoRG2" -Location "West US" -AssignUserIdentity $UAMI ``` -------------------------------- ### Connect using a certificate thumbprint Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Requires the certificate to be installed in the user certificate store on Windows. ```PowerShell Connect-ExchangeOnline -CertificateThumbPrint "012THISISADEMOTHUMBPRINT" -AppID "36ee4c6c-0812-40a2-b820-b22ebd02bce3" -Organization "contosoelectronics.onmicrosoft.com" ``` ```PowerShell Connect-IPPSSession -CertificateThumbPrint "012THISISADEMOTHUMBPRINT" -AppID "36ee4c6c-0812-40a2-b820-b22ebd02bce3" -Organization "contosoelectronics.onmicrosoft.com" ``` -------------------------------- ### Verify module import status Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Check the provisioning state of the imported module to ensure it has successfully installed. ```PowerShell Get-AzAutomationModule -ResourceGroupName ContosoRG -AutomationAccountName ContosoAzAuto1 -Name ExchangeOnlineManagement ``` -------------------------------- ### Connect to Exchange Online in Azure Automation Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Example of the initial connection command required within an Azure Automation PowerShell runbook. ```PowerShell Connect-ExchangeOnline -ManagedIdentity -Organization contoso.onmicrosoft.com -ManagedIdentityAccountId bf6dcc76-4331-4942-8d50-87ea41d6e8a1 ``` -------------------------------- ### Retrieve Mailbox Folder Permissions Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Examples of using different identity parameters to retrieve folder permissions. ```PowerShell Get-MailboxFolderPermission -Identity : ``` ```PowerShell Get-MailboxFolderPermission -Identity :\ ``` -------------------------------- ### Get User Credentials Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-servers-using-remote-powershell Prompts the user for their credentials to be used in subsequent connection commands. ```PowerShell $UserCredential = Get-Credential ``` -------------------------------- ### Wildcard Usage in OPATH Source: https://learn.microsoft.com/en-us/powershell/exchange/recipient-filters Examples of using the -like operator with wildcards in Exchange Online PowerShell. ```powershell "Department -like 'sales*'" ``` ```powershell "Department -like '*sales'" ``` -------------------------------- ### Create a single connection using a PowerShell runspace Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exo-powershell-c-sharp Demonstrates initializing a runspace with the ExchangeOnlineManagement module and executing Connect-ExchangeOnline followed by an Exchange cmdlet. ```C# using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Security; void SingleConnectionToExchangeOnline() { // Setup the Initial Session State of each runspace in the pool // Import the ExchangeOnlineManagement module. // Set the Execution Policy of the runspace. InitialSessionState iss = InitialSessionState.CreateDefault(); iss.ImportPSModule(new string[] { "ExchangeOnlineManagement" }); iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned; iss.ThrowOnRunspaceOpenError = true; Runspace runspace = RunspaceFactory.CreateRunspace(iss); runspace.Open(); // Run the Connect-ExchangeOnline command in the runspace to create a connection with EXO. PowerShell ps = PowerShell.Create(runspace); ps.AddCommand("Connect-ExchangeOnline"); ps.AddParameters(new Dictionary { ["Organization"] = "contoso.onmicrosoft.com", ["CertificateFilePath"] = "C:\\Users\\Certificates\\mycert.pfx", ["CertificatePassword"] = GetPassword(), ["AppID"] = "a37927a4-1a1a-4162-aa29-e346d5324590" }); // Execute the script synchronously. Collection connectionResult = ps.Invoke(); // Clear the connection commands before running cmdlets. ps.Commands.Clear(); // Create a new command to execute an Exchange Online cmdlet. ps.AddCommand("Get-Mailbox"); ps.AddParameter("Identity", "ContosoUser1"); Collection results = ps.Invoke(); // Check if there were any errors. if (!ps.HadErrors) { // Write the results to console. foreach (PSObject result in results) { Console.WriteLine(result.ToString()); } } else { // Write the errors to console by accessing the error stream of the Powershell object. foreach (ErrorRecord error in ps.Streams.Error) { Console.WriteLine(error.ToString()); } } } SecureString GetPassword() { // Return the Password as a SecureString } ``` -------------------------------- ### Connect using a local certificate Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Uses a local .pfx file for authentication. ```PowerShell Connect-ExchangeOnline -CertificateFilePath "C:\Users\navin\Desktop\automation-cert.pfx" -CertificatePassword (Get-Credential).password -AppID "36ee4c6c-0812-40a2-b820-b22ebd02bce3" -Organization "contosoelectronics.onmicrosoft.com" ``` ```PowerShell Connect-IPPSSession -CertificateFilePath "C:\Users\navin\Desktop\automation-cert.pfx" -CertificatePassword (Get-Credential).password -AppID "36ee4c6c-0812-40a2-b820-b22ebd02bce3" -Organization "contosoelectronics.onmicrosoft.com" ``` -------------------------------- ### Uninstall Exchange Online Module Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Remove the module from the system. Elevated privileges are required if installed for all users. ```PowerShell Uninstall-Module -Name ExchangeOnlineManagement ``` -------------------------------- ### Find Available Module Versions Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 List all available versions of the module, including preview releases. ```PowerShell Find-Module ExchangeOnlineManagement -AllVersions -AllowPrerelease ``` -------------------------------- ### Enable Error Reporting for Preview Versions Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Use this command to generate log files for troubleshooting preview versions of the module. Replace with your desired output directory. ```PowerShell Connect-ExchangeOnline -EnableErrorReporting -LogDirectoryPath -LogLevel All ``` -------------------------------- ### Connect-ExchangeOnline syntax Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Displays the syntax for the Connect-ExchangeOnline cmdlet with available parameters. ```PowerShell Connect-ExchangeOnline [-UserPrincipalName ] [-ExchangeEnvironmentName ] [-ShowBanner:$false] [-LoadCmdletHelp] [-DelegatedOrganization ] [-SkipLoadingFormatData] [-DisableWAM] ``` -------------------------------- ### Store User-Assigned Managed Identity ClientId Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Syntax and example for retrieving and storing the ClientId of a user-assigned managed identity. ```PowerShell $MI_ID = (Get-AzUserAssignedIdentity -Name "" -ResourceGroupName "").ClientId ``` ```PowerShell $MI_ID = (Get-AzUserAssignedIdentity -Name "ContosoMI1" -ResourceGroupName "ContosoRG2").ClientId ``` -------------------------------- ### Connect to specialized environments Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Commands for connecting to GCC High, DoD, and China environments. ```PowerShell Connect-ExchangeOnline -ExchangeEnvironmentName O365USGovGCCHigh Connect-IPPSSession -ConnectionUri https://ps.compliance.protection.office365.us/powershell-liveid/ -AzureADAuthorizationEndpointUri https://login.microsoftonline.us/organizations ``` ```PowerShell Connect-ExchangeOnline -ExchangeEnvironmentName O365USGovDoD Connect-IPPSSession -ConnectionUri https://compliance.dod.microsoft.com/powershell-liveid -AzureADAuthorizationEndpointUri https://login.microsoftonline.us/organizations ``` ```PowerShell Connect-ExchangeOnline -ExchangeEnvironmentName O365China Connect-IPPSSession -ConnectionUri https://ps.compliance.protection.partner.outlook.cn/powershell-liveid -AzureADAuthorizationEndpointUri https://login.chinacloudapi.cn/organizations ``` -------------------------------- ### Register PowerShell Gallery Repository Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Run this command to set the default repository to PSGallery if the module cannot be found. ```PowerShell Register-PSRepository -Default ``` -------------------------------- ### Set Default Sublabel via PowerShell Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Configures a default sublabel for a parent label using the DefaultSubLabelId key and a GUID. ```powershell Set-Label -Identity "Confidential" -AdvancedSettings @{DefaultSubLabelId="8faca7b8-8d20-48a3-8ea2-0f96310a848e"} ``` -------------------------------- ### Connect to Security & Compliance PowerShell environments Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-scc-powershell Use these commands to initiate an interactive session with specific Microsoft 365 cloud environments. ```PowerShell Connect-IPPSSession -UserPrincipalName navin@contoso.onmicrosoft.com ``` ```PowerShell Connect-IPPSSession -UserPrincipalName chris@govt.us -ConnectionUri https://ps.compliance.protection.office365.us/powershell-liveid/ -AzureADAuthorizationEndpointUri https://login.microsoftonline.us/organizations ``` ```PowerShell Connect-IPPSSession -UserPrincipalName michelle@govt.mil -ConnectionUri https://l5.ps.compliance.protection.office365.us/powershell-liveid/ -AzureADAuthorizationEndpointUri https://login.microsoftonline.us/organizations ``` ```PowerShell Connect-IPPSSession -UserPrincipalName li@fabrikam.cn -ConnectionUri https://ps.compliance.protection.partner.outlook.cn/powershell-liveid -AzureADAuthorizationEndpointUri https://login.chinacloudapi.cn/organizations ``` -------------------------------- ### Enable Container Support via PowerShell Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Configures the client to remove encryption from PST, RAR, and 7zip files. ```PowerShell Set-LabelPolicy -Identity Global -AdvancedSettings @{EnableContainerSupport="True"} ``` -------------------------------- ### Update distribution group members in bulk Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Example of a bulk update operation that may exceed the 15-minute REST API timeout limit. ```PowerShell $Members = @("member1","member2",...,"member10000") Update-DistributionGroupMember -Identity DG01 -Members $Members ``` -------------------------------- ### Connect to Azure Az PowerShell Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Initializes the Azure PowerShell session. ```PowerShell Connect-AzAccount ``` -------------------------------- ### Connect to Customer Organizations Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Connect to a customer organization using CSP, GDAP, or guest account credentials. ```PowerShell Connect-ExchangeOnline -UserPrincipalName navin@contoso.onmicrosoft.com -DelegatedOrganization adatum.onmicrosoft.com ``` -------------------------------- ### Configure PFileSupportedExtensions Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Defines which file types are subject to encryption. Use the asterisk for all types or a JSON-formatted string for specific extensions. ```PowerShell Set-LabelPolicy -Identity Scanner -AdvancedSettings @{PFileSupportedExtensions="*"} ``` ```PowerShell Set-LabelPolicy -Identity Scanner -AdvancedSettings @{PFileSupportedExtensions=ConvertTo-Json(".txt", ".csv")} ``` -------------------------------- ### Connect to a customer organization Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-scc-powershell Connect to a customer organization using CSP, GDAP, or guest accounts. Requires version 3.0.0 or later of the module. ```PowerShell Connect-IPPSSession -UserPrincipalName navin@contoso.onmicrosoft.com -DelegatedOrganization adatum.onmicrosoft.com -AzureADAuthorizationEndpointUri https://login.microsoftonline.com/adatum.onmicrosoft.com ``` -------------------------------- ### Connect to Exchange Online by Environment Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Connect to different Microsoft 365 cloud environments using a user principal name. ```PowerShell Connect-ExchangeOnline -UserPrincipalName navin@contoso.onmicrosoft.com ``` ```PowerShell Connect-ExchangeOnline -UserPrincipalName laura@blueyonderairlines.us -ExchangeEnvironmentName O365USGovGCCHigh ``` ```PowerShell Connect-ExchangeOnline -UserPrincipalName julia@adatum.mil -ExchangeEnvironmentName O365USGovDoD ``` ```PowerShell Connect-ExchangeOnline -UserPrincipalName lukas@fabrikam.de -ExchangeEnvironmentName O365GermanyCloud ``` -------------------------------- ### Connect to Security & Compliance PowerShell Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-scc-powershell Use this syntax to authenticate with the service. Include the -EnableSearchOnlySession switch if you intend to run eDiscovery cmdlets. ```PowerShell Connect-IPPSSession -UserPrincipalName [-ConnectionUri ] [-AzureADAuthorizationEndpointUri ] [-DelegatedOrganization ] [-PSSessionOption $ProxyOptions] [-EnableSearchOnlySession] ``` -------------------------------- ### Test Exchange Online Command in Runbook Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity A simple command to verify connectivity after establishing the session in an Azure Automation runbook. ```PowerShell Get-AcceptedDomain | Format-Table Name ``` -------------------------------- ### Connect to a CSP organization using the module Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Connects to a customer organization using a CSP account via the Exchange Online PowerShell module. ```PowerShell Connect-ExchangeOnline -UserPrincipalName admin@contoso.onmicrosoft.com -DelegatedOrganization delegated.onmicrosoft.com ``` -------------------------------- ### Load the Exchange Online PowerShell module Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-scc-powershell Run this command to load the module into your current PowerShell session. ```PowerShell Import-Module ExchangeOnlineManagement ``` -------------------------------- ### Create an Azure Resource Group Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Creates a new resource group for hosting Azure resources. ```PowerShell New-AzResourceGroup -Name "" -Location "" ``` ```PowerShell New-AzResourceGroup -Name "ContosoRG" -Location "West US" ``` -------------------------------- ### Identify REST API Session for Get-EXO Cmdlets Source: https://learn.microsoft.com/en-us/powershell/exchange/exchange-online-powershell-v2 Run this command to determine which connection is currently being used by the Get-EXO* cmdlets when multiple sessions are open. ```PowerShell Get-ConnectionInformation | Where-Object {$_.ConnectionUsedForInbuiltCmdlets -eq $true} ``` -------------------------------- ### Connect to Exchange Online with OAuth Token Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Establishes a session using an OAuth token passed as a credential. ```PowerShell $oauthTokenAsPassword = ConvertTo-SecureString '' -AsPlainText -Force $o365cred = New-Object System.Management.Automation.PSCredential ("admin@contoso.onmicrosoft.com", $oauthTokenAsPassword) $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveID/?BasicAuthToOAuthConversion=true&email=SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@contoso.onmicrosoft.com -Credential $o365cred -Authentication Basic -AllowRedirection Import-PSSession $Session ``` -------------------------------- ### Generate a certificate using a script Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Uses the Create-SelfSignedCertificate script to generate SHA1 certificates. ```PowerShell .\Create-SelfSignedCertificate.ps1 -CommonName "MyCompanyName" -StartDate 2026-01-06 -EndDate 2027-01-06 ``` -------------------------------- ### Enable native encryption for all PFile extensions Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Configures the policy to change all PFile extensions to native encryption format. ```PowerShell Set-LabelPolicy -AdvancedSettings @{ AdditionalPPrefixExtensions ="*"} ``` -------------------------------- ### Find ExchangeOnlineManagement module versions Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Commands to identify the latest GA or preview versions of the module available in the PowerShell Gallery. ```PowerShell Find-Module ExchangeOnlineManagement ``` ```PowerShell Find-Module ExchangeOnlineManagement -AllowPrerelease ``` -------------------------------- ### Launch Exchange Management Shell via Command Prompt Source: https://learn.microsoft.com/en-us/powershell/exchange/open-the-exchange-management-shell Commands to initiate the Exchange Management Shell on Windows Server 2019 Core for Mailbox and Edge Transport server roles. ```dos LaunchEMS ``` ```dos exshell.psc1 & exchange.ps1 ``` -------------------------------- ### Import Exchange Cmdlets Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-servers-using-remote-powershell Imports the Exchange cmdlets from the established session into the local PowerShell environment. ```PowerShell Import-PSSession $Session -DisableNameChecking ``` -------------------------------- ### Enable NTFS Owner Preservation Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Configures the label policy to preserve the original NTFS owner when applying sensitivity labels. Use with caution when using the scanner due to potential network latency risks. ```PowerShell Set-LabelPolicy -Identity Global -AdvancedSettings @{UseCopyAndPreserveNTFSOwner ="true"} ``` -------------------------------- ### Connect to a CSP organization using legacy Basic authentication Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Historical method for connecting to a CSP organization using Basic authentication. This method is no longer supported. ```PowerShell $secpasswd = ConvertTo-SecureString '' -AsPlainText -Force $o365cred = New-Object System.Management.Automation.PSCredential ("admin@contoso.onmicrosoft.com", $secpasswd) $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveID/?DelegatedOrg=delegated.onmicrosoft.com&email=SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@delegated.onmicrosoft.com -Credential $o365cred -Authentication Basic -AllowRedirection Import-PSSession $Session ``` -------------------------------- ### Connect to Microsoft Graph PowerShell Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Establishes a connection to Microsoft Graph with the necessary directory permissions. ```PowerShell Connect-MgGraph -Scopes RoleManagement.ReadWrite.Directory ``` -------------------------------- ### Create an Automation Account with Managed Identity Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Provisions an Automation account with a system-assigned managed identity enabled. ```PowerShell New-AzAutomationAccount -Name "" -ResourceGroupName "" -Location "" -AssignSystemIdentity ``` ```PowerShell New-AzAutomationAccount -Name "ContosoAzAuto1" -ResourceGroupName "ContosoRG" -Location "West US" -AssignSystemIdentity ``` -------------------------------- ### Connect to Exchange Online with interactive prompt Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Uses the Exchange Online PowerShell module to initiate a connection with an interactive credential prompt. ```PowerShell Connect-ExchangeOnline -UserPrincipalName admin@contoso.onmicrosoft.com ``` -------------------------------- ### Connect to Exchange Online using legacy Basic authentication Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Historical method using Basic authentication. This method is no longer supported. ```PowerShell $secpasswd = ConvertTo-SecureString '' -AsPlainText -Force $o365cred = New-Object System.Management.Automation.PSCredential ("admin@contoso.onmicrosoft.com", $secpasswd) $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveID/ -Credential $o365cred -Authentication Basic -AllowRedirection Import-PSSession $Session ``` -------------------------------- ### Create a Remote PSSession Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-servers-using-remote-powershell Establishes a new remote PowerShell session to the specified Exchange server using Kerberos authentication. ```PowerShell $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http:///PowerShell/ -Authentication Kerberos -Credential $UserCredential ``` -------------------------------- ### Create a dynamic distribution group with precanned filters Source: https://learn.microsoft.com/en-us/powershell/exchange/recipient-filters Uses specific parameters to define recipient scope, location, and conditional attributes for a new dynamic distribution group. ```PowerShell New-DynamicDistributionGroup -Name "Contoso Finance" -OrganizationalUnit Contoso.com/Users -RecipientContainer Contoso.com/Users -IncludedRecipients MailboxUsers -ConditionalDepartment "Finance" -ConditionalCompany "Contoso" ``` -------------------------------- ### Configure OfficeContentExtractionTimeout Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Sets the timeout for auto-labeling Office files. It is recommended not to exceed 15 seconds. ```PowerShell Set-LabelPolicy -Identity Global -AdvancedSettings @{OfficeContentExtractionTimeout="00:00:15"} ``` -------------------------------- ### Create and store service principal object Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Create a service principal object in Exchange Online and store it in a variable for role assignment. ```PowerShell New-ServicePrincipal -AppId $.AppId -ObjectId $.Id -DisplayName "" $ = Get-ServicePrincipal -Identity "" ``` ```PowerShell New-ServicePrincipal -AppId $AzureADApp.AppId -ObjectId $AzureADApp.Id -DisplayName "SP for Azure AD App ExO PowerShell CBA" $SP = Get-ServicePrincipal -Identity "SP for Azure AD App ExO PowerShell CBA" ``` -------------------------------- ### Find user identity using Invoke-Command vs REST API Source: https://learn.microsoft.com/en-us/powershell/exchange/invoke-command-workarounds-rest-api Compares retrieving user identity details via a remote PSSession versus a direct REST API connection. ```PowerShell Invoke-Command -Session $Session -ScriptBlock {Get-User $Using:Us | Select-Object DistinguishedName, ExternalDirectoryObjectId} -ErrorAction SilentlyContinue ``` ```PowerShell Get-User $Us | Format-List DistinguishedName, ExternalDirectoryObjectId ``` -------------------------------- ### Set default PFile behavior Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Configures the policy to use default behavior where protected files retain the .pfile extension. ```PowerShell Set-LabelPolicy -AdvancedSettings @{ AdditionalPPrefixExtensions =""} ``` -------------------------------- ### Generate and export a self-signed certificate Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Creates a self-signed certificate and exports both the private key (.pfx) and public certificate (.cer) files. ```PowerShell # Create a self-signed certificate $mycert = New-SelfSignedCertificate -DnsName "contoso.org" -CertStoreLocation "cert:\CurrentUser\My" -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange # Export the X.509 certificate and the associated private key to a password-protected .pfx file $mycert | Export-PfxCertificate -FilePath mycert.pfx -Password (Get-Credential).password # Export the X.509 public certificate to a .cer file $mycert | Export-Certificate -FilePath mycert.cer ``` -------------------------------- ### Configure ScannerConcurrencyLevel via PowerShell Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Sets the number of concurrent threads for the scanner service using the Set-LabelPolicy cmdlet. ```PowerShell Set-LabelPolicy -Identity Scanner -AdvancedSettings @{ScannerConcurrencyLevel="8"} ``` -------------------------------- ### Retrieve Connection Information for REST API Sessions Source: https://learn.microsoft.com/en-us/powershell/exchange/invoke-command-workarounds-rest-api Captures connection details for specific REST API modules based on their prefix. ```PowerShell $ConnectionInfo1 = Get-ConnectionInformation | Where-Object { $_.ModulePrefix -eq "C1"} ``` ```PowerShell $ConnectionInfo1 = Get-ConnectionInformation | Where-Object { $_.ModulePrefix -eq "C2"} ``` -------------------------------- ### Connect to a CSP organization using legacy OAuth token Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Historical method for connecting to a CSP organization using an OAuth token. This method is no longer supported. ```PowerShell $oauthTokenAsPassword = ConvertTo-SecureString '' -AsPlainText -Force $o365cred = New-Object System.Management.Automation.PSCredential ("admin@contoso.onmicrosoft.com", $oauthTokenAsPassword) $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveID/? DelegatedOrg=delegated.onmicrosoft.com&BasicAuthToOAuthConversion=true&email=SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@delegated.onmicrosoft.com -Credential $o365cred -Authentication Basic -AllowRedirection Import-PSSession $Session ``` -------------------------------- ### Enable Globalization Features Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Enables classification globalization features for 64-bit processes to improve support for East Asian languages and double-byte characters. ```PowerShell Set-LabelPolicy -Identity Global -AdvancedSettings @{EnableGlobalization="True"} ``` -------------------------------- ### Store Microsoft Entra application details Source: https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2 Connect to Microsoft Graph and retrieve the service principal details for the registered application. ```PowerShell Connect-MgGraph -Scopes AppRoleAssignment.ReadWrite.All,Application.Read.All $ = Get-MgServicePrincipal -Filter "DisplayName eq ''" ``` ```PowerShell Connect-MgGraph -Scopes AppRoleAssignment.ReadWrite.All,Application.Read.All $AzureADApp = Get-MgServicePrincipal -Filter "DisplayName eq 'ExO PowerShell CBA'" ``` -------------------------------- ### Connect to Exchange Online from an Azure VM Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Command to initiate a connection from within an Azure VM using a system-assigned managed identity. ```PowerShell Connect-ExchangeOnline -ManagedIdentity -Organization contoso.onmicrosoft.com ``` -------------------------------- ### Connect to Microsoft Graph PowerShell Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Establishes a connection to Microsoft Graph with the necessary permissions for managing app role assignments. ```PowerShell Connect-MgGraph -Scopes AppRoleAssignment.ReadWrite.All,Application.Read.All ``` -------------------------------- ### Enable LogMatchedContent in Label Policy Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Configures the label policy to send content matches for sensitive info types to Microsoft Purview. ```PowerShell Set-LabelPolicy -Identity Global -AdvancedSettings @{LogMatchedContent="True"} ``` -------------------------------- ### List Role Assignments for Found Roles Source: https://learn.microsoft.com/en-us/powershell/exchange/find-exchange-cmdlet-permissions Displays the role assignments associated with the roles identified in the previous step. ```PowerShell $Perms | foreach {Get-ManagementRoleAssignment -Role $_.Name -Delegating $false | Format-Table -Auto Role,RoleAssigneeType,RoleAssigneeName} ``` -------------------------------- ### Connect to Exchange Online via OAuth Token Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-to-exchange-online-powershell Establish a PSSession using an encoded OAuth token for a delegated organization. ```PowerShell $oauthTokenAsPassword = ConvertTo-SecureString '' -AsPlainText -Force $o365cred = New-Object System.Management.Automation.PSCredential ("admin@contoso.onmicrosoft.com", $oauthTokenAsPassword) $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/PowerShell-LiveID/?DelegatedOrg=delegated.onmicrosoft.com&BasicAuthToOAuthConversion=true&email=SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@delegated.onmicrosoft.com -Credential $o365cred -Authentication Basic -AllowRedirection Import-PSSession $Session ``` -------------------------------- ### Verify Exchange.ManageAsApp Permission Availability Source: https://learn.microsoft.com/en-us/powershell/exchange/connect-exo-powershell-managed-identity Lists the available app roles for the Exchange Online service principal to confirm the presence of the Exchange.ManageAsApp permission. ```PowerShell Get-MgServicePrincipal -Filter "AppId eq '00000002-0000-0ff1-ce00-000000000000'" | Select-Object -ExpandProperty AppRoles | Format-Table Value,Id ``` -------------------------------- ### Enable Custom Permissions for Protected Files Source: https://learn.microsoft.com/en-us/powershell/exchange/client-advanced-settings Configures the policy to allow users to view and modify custom permissions on encrypted documents via File Explorer. ```PowerShell Set-LabelPolicy -Identity Global -AdvancedSettings @{EnableCustomPermissionsForCustomProtectedFiles="True"} ```