Connect to exchange online powershell

FileList

  • ExchangeOnlineManagement.nuspec
  • ExchangeOnlineManagement.psd1
  • license.txt
  • en-US\ExchangeOnlineManagement-Help.xml
  • en-US\Microsoft.Exchange.Management.RestApiClient.dll-Help.xml
  • netCore\ExchangeOnlineManagement.psm1
  • netCore\Microsoft.Exchange.Management.AdminApiProvider.dll
  • netCore\Microsoft.Exchange.Management.ExoPowershellGalleryModule.deps.json
  • netCore\Microsoft.Exchange.Management.ExoPowershellGalleryModule.dll
  • netCore\Microsoft.Exchange.Management.RestApiClient.dll
  • netCore\Microsoft.Identity.Client.dll
  • netCore\Microsoft.IdentityModel.JsonWebTokens.dll
  • netCore\Microsoft.IdentityModel.Logging.dll
  • netCore\Microsoft.IdentityModel.Tokens.dll
  • netCore\Microsoft.OData.Client.dll
  • netCore\Microsoft.OData.Core.dll
  • netCore\Microsoft.OData.Edm.dll
  • netCore\Microsoft.Online.CSE.RestApiPowerShellModule.Instrumentation.dll
  • netCore\Microsoft.Spatial.dll
  • netCore\Microsoft.Win32.Registry.AccessControl.dll
  • netCore\Newtonsoft.Json.dll
  • netCore\System.Configuration.ConfigurationManager.dll
  • netCore\System.Diagnostics.PerformanceCounter.dll
  • netCore\System.IdentityModel.Tokens.Jwt.dll
  • netCore\System.IO.Abstractions.dll
  • netCore\System.Management.Automation.dll
  • netCore\System.Runtime.CompilerServices.Unsafe.dll
  • netCore\System.Security.Cryptography.Pkcs.dll
  • netCore\System.Security.Cryptography.ProtectedData.dll
  • netCore\System.Security.Permissions.dll
  • netCore\System.Text.Encoding.CodePages.dll
  • netFramework\Create-SelfSignedCertificate.ps1
  • netFramework\ExchangeOnlineManagement.psm1
  • netFramework\Microsoft.Exchange.Management.AdminApiProvider.dll
  • netFramework\Microsoft.Exchange.Management.ExoPowershellGalleryModule.dll
  • netFramework\Microsoft.Exchange.Management.RestApiClient.dll
  • netFramework\Microsoft.Identity.Client.dll
  • netFramework\Microsoft.Identity.Client.xml
  • netFramework\Microsoft.IdentityModel.Clients.ActiveDirectory.dll
  • netFramework\Microsoft.IdentityModel.Clients.ActiveDirectory.xml
  • netFramework\Microsoft.OData.Client.dll
  • netFramework\Microsoft.OData.Client.xml
  • netFramework\Microsoft.OData.Core.dll
  • netFramework\Microsoft.OData.Core.xml
  • netFramework\Microsoft.OData.Edm.dll
  • netFramework\Microsoft.OData.Edm.xml
  • netFramework\Microsoft.Online.CSE.RestApiPowerShellModule.Instrumentation.dll
  • netFramework\Microsoft.Spatial.dll
  • netFramework\Microsoft.Spatial.xml
  • netFramework\Newtonsoft.Json.dll
  • netFramework\Newtonsoft.Json.xml
  • netFramework\System.IO.Abstractions.dll
  • netFramework\System.Management.Automation.dll
  • netFramework\ref\Microsoft.Exchange.Management.ExoPowershellGalleryModule.dll

Conclusion

Exchange Online PowerShell Version 2 is the current version of the Exchange cmdlets. It runs on PowerShell 7 which is able to leverage modern authentication on multiple platforms, including Azure Cloud Shell, Microsoft Windows and Apple MacOS. Installation is quick and straightforward on all platforms and in the case of Azure cloud Shell is simply built in.

Connecting to Exchange Online is an identical experience on all three platforms, using browser based SSO, which allows us to integrate with Multi Factor Authentication. Once you connect to Exchange Online Powershell you can administer Exchange Online, irrespective of platform or operating system in a supported manner.

Was this helpful?

Do you want to become a member of Altaro Dojo?

Connect to Exchange Online (Microsoft 365)

  1. Verify the requirements for Exchange Online (Microsoft 365)
  2. Start Windows PowerShell in administrator mode
  3. Verify your Execution policy settings by running the below command:

    Get-ExecutionPolicy

    The execution policy is normally set to Restricted. It is advised to configure the policy to RemoteSigned in order to connect to Exchange Online with PowerShell successfully:

    Set-ExecutionPolicy RemoteSigned

  4. Run the following command and enter your Microsoft 365 global admin credentials:

    $LiveCred = Get-Credential

  5. Run the following command to connect to Exchange Online (Microsoft 365)

    Connect-ExchangeOnline -Credential $LiveCred

    Use the Connect-ExchangeOnline cmdlet without the -Credential parameter if you’re connecting to Exchange Online using an account that has MFA enabled. Provide your credentials in a pop-up window.

    Note that if you have your account with MFA enabled, the cmdlet doesn’t accept the -Credential parameter.

  6. Run the following command to disconnect Exchange Online

    Disconnect-ExchangeOnline

How the Exchange Online PowerShell v2 module (EXO V2 module) works

The EXO V2 module uses modern authentication for all cmdlets. You can’t use Basic authentication in the EXO V2 module; however, you still need to enable the Basic authentication setting in WinRM as explained later in this article.

The module contains a small set of exclusive Exchange Online PowerShell cmdlets that are optimized for bulk data retrieval scenarios (think: thousands and thousands of objects). When you first open the module, you’ll only see these exclusive cmdlets. After you connect to your Exchange Online organization, you’ll see all of the familiar cmdlets (Exchange Online PowerShell commands) that are available in Exchange Online PowerShell.

The Exchange Online cmdlets in the EXO V2 module are meant to replace their older, less efficient equivalents, but the equivalent cmdlets are still available (after you connect).

The improved Exchange Online PowerShell cmdlets that are only available in the EXO V2 module are listed in the following table:

Exchange Online PowerShell commands

Older related cmdlet EXO V2 module cmdlet
Get-Mailbox Get-EXOMailbox
Get-Recipient Get-EXORecipient
Get-CASMailbox Get-EXOCasMailbox
Get-MailboxPermission Get-EXOMailboxPermission
Get-RecipientPermission Get-EXORecipientPermission
Get-MailboxStatistics Get-EXOMailboxStatistics
Get-MailboxFolderStatistics Get-EXOMailboxFolderStatistics
Get-MailboxFolderPermission Get-EXOMailboxFolderPermission
Get-MobileDeviceStatistics Get-EXOMobileDeviceStatistics

The connection-related cmdlets that are available in the EXO V2 module are listed in the following table:

Older related cmdlet EXO V2 module cmdlet
Connect-EXOPSSession or New-PSSession Connect-ExchangeOnline
Connect-IPPSSession Connect-IPPSSession
Remove-PSSession Disconnect-ExchangeOnline

Miscellaneous Exchange Online cmdlets that happen to be in the EXO V2 module are listed in the following table:

EXO V2 module cmdlet Comments
Get-MyAnalyticsFeatureConfig Available in v2.0.4 or later.
Set-MyAnalyticsFeatureConfig Available in v2.0.4 or later.
Get-UserBriefingConfig Replaced by Get-MyAnalyticsFeatureConfig.
Set-UserBriefingConfig Replaced by Set-MyAnalyticsFeatureConfig.
Get-VivaInsightsSettings Available in v2.0.5-Preview2 or later.
Set-VivaInsightsSettings Available in v2.0.5-Preview2 or later.

View Microsoft 365 Business Premium – Latest Pricing

Ограничение на размер письма (вложения)

При отправке и получении писем, Exchange не пропускаем письма больших размеров (как правило, из-за тяжелого вложения). Это помогает предотвратить переполнение почтовых баз и замедление скорости работы. Однако, значения по умолчанию, скорее всего, не будут для нас оптимальными и необходимо будет их сменить.

Данный лимит может задаваться на 3-х уровнях. Разберем, как их можно посмотреть и поменять.

1) Транспорт организации. Глобальный уровень. Имеет наименьший приоритет.

Посмотреть заданные значения можно командой:

Get-TransportConfig | fl MaxSendSize, MaxReceiveSize

* где MaxSendSize — максимальный размер отправляемого письма; MaxReceiveSize — принимаемого.

Задать значения можно командой:

Set-TransportConfig -MaxSendSize 70MB -MaxReceiveSize 70MB

2) Коннектор. Настраивается на отдельном сервере Exchange. Приоритет выше, чем у транспорта организации. Коннекоторов может быть несколько — вывести их список можно командой:

Get-ReceiveConnector

* коннекторы приемки для всех серверов Exchange.

Get-SendConnector

* коннекторы отправки.

После мы можем посмотреть ограничение на объем письма для коннектора, например:

Get-ReceiveConnector «Exchange01\Connector02» | fl MaxmessageSize

* в данном примере мы увидим ограничение для коннектора Connector02 на сервере Exchange01.

Теперь, чтобы изменить ограничение для коннектора вводим команду:

Set-ReceiveConnector «Exchange01\Connector02» -MaxMessageSize 73Mb

* коннектор приемки Connector02 на сервере Exchange01 будет пропускать сообщения объемом 73 Мб.

3) Почтовый ящик. Максимальный приоритет. Посмотреть ограничение для пользователя можно командой:

Get-Mailbox user1 | fl MaxSendSize, MaxReceiveSize

* по умолчанию, ограничение выставлено в значение unlimited. Таким образом, контроль выполняется на уровне коннекторов и транспорта.

Задать индивидуальное ограничение для пользователя можно командой:

Set-Mailbox user1 -MaxSendSize 75MB -MaxReceiveSize 75MB

Размер вложения

Справедливости ради, нужно заметить, что вышеописанный способ по ограничению объема отправляемого письма накладывает лимит на все сообщение в целом (и текст, и вложение). Но в Exchange можно создать транспортное правило, которое будет проверять размер именно вложения.

Правило можно создать командой:

New-TransportRule -Name AttachmentLimit -AttachmentSizeOver 65MB -RejectMessageReasonText «Sorry, messages with attachments over 65 MB are not accepted.»

PowerShell Script

In order to make a set of code more accessible to Admins that may or may not have as much PowerShell coding experience, we can create a GUI-like experience with PowerShell to run through the Prerequisite checks.

For example, if we make the script menu-driven, our PowerShell script can provide an experience where they just need to select which options to run. Additionally, we can output details to a CSV file that contain lists of users to check. If the script were to cover all aspects of a migration, then the menu might look something like this:

Simple menu-driven PowerShell script

Note that we have a menu item for each major part of the move process: prerequisite checks, mailbox moves and reporting. For the Prerequisite submenu, we would then be able to shape the menu to include the prerequisite checks we covered in this article, like so:

PowerShell script for executing prerequisite checks

And now we have a script that can be used to drive a migration for our mailbox moves from Exchange to Exchange Online.

Mailbox and Distribution Group Management

Create user mailbox

PS > password = Read-Host «Enter password» -AsSecureString

Enter password: *********

PS > New-Mailbox -UserPrincipalName [email protected] -Alias Contact -Name Contact -OrganizationalUnit Users -Password $password -FirstName Nicolas -LastName PRIGENT -DisplayName «Nicolas PRIGENT» -ResetPasswordOnNextLogon $true

1
2
3
4
5

PS>password=Read-Host»Enter password»-AsSecureString

Enter password*********

PS>New-Mailbox-UserPrincipalName [email protected] Contact-Name Contact-OrganizationalUnit Users-Password$password-FirstName Nicolas-LastName PRIGENT-DisplayName»Nicolas PRIGENT»-ResetPasswordOnNextLogon$true

PS > New-Mailbox -Name «<Identity>» –Room

1 PS>New-Mailbox-Name»<Identity>»–Room

PS > New-Mailbox -Name «<Name>» -Equipment

1 PS>New-Mailbox-Name»<Name>»-Equipment

Create distribution group

PS > New-DistributionGroup -Name «ITDepartment» -Members [email protected]

1 PS>New-DistributionGroup-Name»ITDepartment»-Members [email protected]

Remember that for a New-* cmdlet, there are often (but not always) Get-* and Set-* cmdlets available.

Working Principle

You can connect to Exchange Online PowerShell, but this process is more complicated than using PowerShell for managing a local Exchange Server. However, you can use the built-in PowerShell console to manage remote cloud infrastructures. In this case, the console is called remote PowerShell or PowerShell Remoting. The process of initiating a remote PowerShell session for Office 365 and Exchange Online is slightly different. You should download and install special components before you can open a remote Office 365 session. Fortunately, the cmdlets required to initiate a remote Exchange Online PowerShell are downloaded automatically when you create a remote PowerShell session. Different sets of PowerShell cmdlets are used to manage Microsoft Office 365 and Microsoft Exchange Online.

The main reasoning behind connecting to Microsoft Exchange Online in PowerShell entails the following:

  • Creating a remote session to Exchange Online in PowerShell opened on your local machine.
  • Providing connection settings, passing authentication.
  • Importing PowerShell cmdlets that are needed to manage Exchange Online remotely.

In today’s blog post, we will run PowerShell cmdlets on Windows 10.

Install Exchange Online PowerShell v2 module (EXO V2 module)

To install the EXO V2 module for the first time, complete the following steps:

Install the EXO V2 module

Step 3: Now you can use the Install-Module cmdlet to install the EXO V2 module from the PowerShell Gallery. Typically, you’ll want the latest public version of the module, but you can also install a Preview version if one is available.

To install the latest public version of the module, run one of the following commands:These commands must be run in an elevated PowerShell window (a PowerShell window you open by selecting Run as administrator):

PowerShell

Install-Module -Name ExchangeOnlineManagement

Install the EXO V2 module Only for the current user account:

PowerShell

Install-Module -Name ExchangeOnlineManagement -Scope CurrentUser

To install a Preview version of the module, replace with the necessary value, and run one of the following commands:

In an elevated PowerShell window (all users):

PowerShell

Install-Module -Name ExchangeOnlineManagement -RequiredVersion -AllowPrerelease

Only for the current user account:

PowerShell

Install-Module -Name ExchangeOnlineManagement -RequiredVersion -AllowPrerelease -Scope CurrentUser

When you’re finished, enter Y to accept the license agreement.

For detailed syntax and parameter information, see Install-Module.

Version History

Version Downloads Last updated


3.2.0-Preview3

1,635 4/28/2023


3.2.0-Preview2

3,752 3/20/2023


3.2.0-Preview1

2,109 2/27/2023


3.1.0

1,319,404 1/9/2023


3.1.0-Preview2

1,643 12/19/2022


3.1.0-Preview1

1,433 12/5/2022


3.0.1-Preview1

1,731 11/14/2022


3.0.0

2,437,343 9/19/2022


2.0.6-Preview8

3,314 9/9/2022


2.0.6-Preview7

1,492,298 8/13/2022


2.0.6-Preview6

38,901 5/20/2022


2.0.6-Preview5

43,272 3/17/2022


2.0.6-preview4

3,292 1/13/2022


2.0.6-Preview3

11,577 10/20/2021


2.0.5
(current version)

6,802,061 5/11/2021


2.0.5-Preview2

630 4/30/2021


2.0.5-Preview1

813 4/21/2021


2.0.4

493,193 2/5/2021


2.0.4-Preview9

2,050 1/19/2021


2.0.4-Preview8

254 1/4/2021


2.0.4-Preview6

23,193 11/6/2020


2.0.4-Preview2

104,541 9/22/2020


2.0.3

507,697 9/21/2020


2.0.3-Preview

8,762 6/30/2020


1.0.1

257,527 6/3/2020


0.4578.0

518,499 4/16/2020


0.4368.1

23,377 3/30/2020


0.3582.0

39,344 2/10/2020


0.3555.1

13,866 1/22/2020


0.3374.11

11,970 1/15/2020


0.3374.10

5,475 12/27/2019


0.3374.9

17,553 11/26/2019


0.3374.4

7,696 10/31/2019


0.3374.1

812 10/25/2019


0.3374.0

599 10/22/2019

Update the EXO V2 module

If the module is already installed on your computer, you can run the following commands to see the version that’s currently installed and update it to the latest version from the PowerShell Gallery:

To see the version of the module that’s currently installed, run the following commands:

PowerShell

Import-Module ExchangeOnlineManagement; Get-Module ExchangeOnlineManagement

You can use the Update-Module cmdlet to update the EXO V2 module from the PowerShell Gallery. Typically, you’ll want the latest public version of the module, but you can also upgrade to a Preview version if one is available.

To upgrade to the latest public version of the module, run one of the following commands based on how you originally installed the module (in an elevated PowerShell window vs. Scope CurrentUser):

In an elevated PowerShell window (all users):

PowerShell

Update-Module -Name ExchangeOnlineManagement

Only for the current user account:

PowerShell

Update-Module -Name ExchangeOnlineManagement -Scope CurrentUser

To upgrade to a Preview version of the module, replace with the necessary value, and run one of the following commands based on how you originally installed the module (in an elevated PowerShell window vs. Scope CurrentUser):

In an elevated PowerShell window (all users):

PowerShell

Update-Module -Name ExchangeOnlineManagement -RequiredVersion -AllowPrerelease

Only for the current user account:

PowerShell

Update-Module -Name ExchangeOnlineManagement -RequiredVersion -AllowPrerelease -Scope CurrentUser

When you’re finished, enter Y to accept the license agreement.

To confirm that the update was successful, run the following commands to check the version information of the module that’s installed:

PowerShell

Import-Module ExchangeOnlineManagement; Get-Module ExchangeOnlineManagement

For detailed syntax and parameter information, see Update-Module.

Alternative Method

Let’s consider one more method that can be used to connect to Exchange Online PowerShell. This method can be considered as a modification of the first method.

1. Create a new profile for PowerShell with the function:

New-item -type file -force $profile

2. Edit the profile configuration file in the text editor to add the function titled Connect-EXOnline:

notepad $profile

3. Add the following content to the PowerShell profile configuration file and change [email protected] to your account name, then save the text file.

Function Connect-EXOnline

{

$credentials = Get-Credential -Credential [email protected]

Write-Output “Getting the Exchange Online cmdlets”

$Session = New-PSSession -ConnectionUri https://outlook.office365.com/powershell-liveid/ `

-ConfigurationName Microsoft.Exchange -Credential $credentials `

-Authentication Basic -AllowRedirection

Import-PSSession $Session

}

4. Close the current PowerShell window and open a new PowerShell window as Administrator. Run the command to connect to Exchange Online PowerShell:

Connect-ExOnline

Enter your password in the popup window.

5. When you have finished working with Exchange Online PowerShell, end the session with the command:

Get-PSSession | Remove-PSSession

Properties and property sets in the EXO V2 module

Traditional Exchange Online cmdlets return all possible object properties in their output, including many properties that are often blank or aren’t interesting in many scenarios. This behavior causes degraded performance (more server computation and added network load). You rarely (if ever) need the full complement of properties in the cmdlet output.

The Get-EXO* cmdlets in the module have categorized output properties. Instead of giving all properties equal importance and returning them in all scenarios, we’ve categorized specific related properties into property sets. Simply put, these property sets are buckets of two or more related properties on the cmdlet.

In the biggest and most used Get-EXO* cmdlets:

  • Get-EXOCasMailbox
  • Get-EXOMailbox
  • Get-EXOMailboxStatistics
  • Get-EXORecipient

Property sets are controlled by the following parameters:

  • PropertySets: This parameter accepts one or more available property set names separated by commas. The available property sets are described in Property sets in Exchange Online PowerShell V2 cmdlets.
  • Properties: This parameter accepts one or more property names separated by commas.

You can use the PropertySets and Properties parameters together in the same command.

We’ve also included a Minimum property set that includes a bare minimum set of required properties for the cmdlet output (for example, identity properties). The properties in the Minimum property sets are also described in Property sets in Exchange Online PowerShell V2 cmdlets.

  • If you don’t use the PropertySets or Properties parameters, you automatically get the properties in the Minimum property set.
  • If you use the PropertySets or Properties parameters, you get the specified properties and the properties in the Minimum property set.

Either way, the cmdlet output will contain far fewer properties, and the time it takes to return those results will be much faster.

For example, after you connect to Exchange Online PowerShell, the following example returns only the properties in the Minimum property set for the first ten mailboxes.

PowerShell

Get-EXOMailbox -ResultSize 10

In contrast, the output of the same Get-Mailbox command would return at least 230 properties for each of the first ten mailboxes.

Note

Although the PropertySets parameter accepts the value All, we highly discourage using this value to retrieve all properties, because it slows down the command and reduces reliability. Always use the PropertySets and Properties parameters to retrieve the minimum number of properties that are required for your scenario.

For more information about filtering in the EXO V2 module, see Filters in the Exchange Online V2 module.

View Microsoft 365 Business Premium – Latest Pricing

Install Exchange Online PowerShell v2 module requirements

Exchange Online PowerShell v2 module requirements (also known as prerequisites for the EXO V2 module) are described below.

The settings described in this section are required in all versions of PowerShell on all operating systems.

Supported operating systems for the EXO V2 module

The latest version of the EXO V2 module is officially supported in PowerShell 7 on , , and Apple macOS.

Specifically, version 2.0.4 or later of the EXO V2 module is supported in PowerShell 7.0.3 or later.

Windows

All versions of the EXO V2 module are supported in Windows PowerShell 5.1.

PowerShell 7 on Windows requires version 2.0.4 or later of the EXO V2 module.

The EXO V2 module is supported in the following versions of Windows:

  • Windows 10
  • Windows 8.14
  • Windows Server 2019
  • Windows Server 2016
  • Windows Server 2012 or Windows Server 2012 R24
  • Windows 7 Service Pack 1 (SP1)1,2,3
  • Windows Server 2008 R2 SP11,2,3

1 This version of Windows has reached its end of support, and is now supported only in Azure virtual machines.

2 This version of Windows doesn’t support version 2.0.4 or later of the EXO V2 module. Only version 2.0.3 or earlier is supported.

3 Windows PowerShell 5.1 on this version of Windows requires the Microsoft .NET Framework 4.5 or later and the Windows Management Framework 5.1. For more information, see Windows Management Framework 5.1.

4 PowerShell 7 on this version of Windows requires the Windows 10 Universal C Runtime (CRT).

How to check PowerShell version in Windows 10
  1. Open PowerShell Window (You don’t need to run it as administrator for this).
  2. Type: “Get-Host” and Press Enter to see your result.
  3. OR Type: “Get-Host | FL version” and Press Enter to see your result.
  4. OR Type: “$PSVersionTable” and Press Enter to see your result.

Check PowerShell version in Windows 10 (3 ways)

Get Execution Policy PowerShell (Set-Execution Policy to RemoteSigned)

To get the Execution Policy setting on your PC do the following:

  1. Open PowerShell Window (You don’t need to Run it as administrator for this).
  2. Type: “Get-ExecutionPolicy” and Press Enter to see your result.

Get Execution Policy

PowerShell needs to be configured to run scripts, and by default, it isn’t. You’ll get the following error when you try to connect:

Files cannot be loaded because running scripts is disabled on this system. Provide a valid certificate with which to sign the files.

To ensure that all PowerShell scripts you download from the internet are signed by a trusted publisher, run the following command in an elevated PowerShell window (a PowerShell window you open by selecting Run as administrator):

PowerShell Script:

Set-ExecutionPolicy RemoteSigned

WinRM needs to allow Basic authentication (it’s enabled by default). We don’t send the username and password combination, but the Basic authentication header is required to send the session’s OAuth token, since the client-side WinRM implementation has no support for OAuth.

Note: You must temporarily enable WinRM to run the following commands. You can enable WinRM by running the command:

(Open Command Prompt (Run as Administrator)

Winrm QuickConfig command

  1. Type “cmd” in the search field
  2. Open best match “Command Prompt App” (Run as Administrator)
  3. type the command below in the command prompt window.

winrm quickconfig

To verify that Basic authentication is enabled for WinRM, run this command in a Command Prompt (not in PowerShell):

Command Prompt (DOS script)

winrm get winrm/config/client/auth

If you don’t see the value Basic = true, you need to run this command in a Command Prompt (not in PowerShell) to enable Basic authentication for WinRM:

Command Prompt (DOS script)

winrm set winrm/config/client/auth @{Basic=”true”}

Note: If you’d rather run the command in PowerShell, enclose this part of the command in quotation marks: ‘@{Basic=”true”}’.

If Basic authentication for WinRM is disabled, you’ll get this error when you try to connect:

The WinRM client cannot process the request. Basic authentication is currently disabled in the client configuration. Change the client configuration and try the request again.

Pre-Checks

1.UPN Match

$CSV = Import-CSV batch1.csvForeach ($Line in $CSV) {$PrimarySMTPAddress = $Line.PrimarySMTPAddress$UPN = (Get-Mailbox $PrimarySMTPAddress).UserPrincipalNameIf ($PrimarySMTPAddress -ne $UPN) {$Output = "The mailbox $PrimarySMTPAddress does not have a matching UPN and is set to $UPN." | Out-File -File $LogDestination -Append}}

An oft asked question is “why are we matching the UPN to a user’s Primary SMTP address?”. Well, simply put, we are following Microsoft’s own recommendation for a better end user experience:

Source: Configuring Alternate Login ID | Microsoft Docs

Remediation

We can also use PowerShell to remediate this issue if you wish to do so. This simple block of code will find the Primary SMTP address of a mailbox and change the UPN to match. It is CSV based:

Foreach ($Line in $CSV) {$Mailbox = Get-Mailbox $Line$PrimarySMTP = $Mailbox.PrimarySMTPAddress$NewUPN = $PrimarySMTPSet-Mailbox $PrimarySMTP -UserPrincipalName $NewUPN}

2. mail.onmicrosoft.com domain check

$Mailboxes = Get-Mailbox -ResultSize UnlimitedForeach ($Mailbox in $Mailboxes) {$DomainFound = $False$EmailAddresses = (Get-Mailbox $Mailbox).EmailAddresses$EmailAddresses | Foreach-Object {If ($_ -like "*mail.onmicrosoft.com") {$DomainFound = $True}}If (!$DomainFound) {Write-host 'Not Found!'} Else {Write-host 'Domain Found'}}

Remediation

$Domain = ‘tenant.mail.onmicrosoft.com’$Alias = ‘Malboxalias’$NewAddress = $Alias+’@’+$DomainSet-Mailbox $PrimarySMTP -EmailAddresses @{Add="$EmailAddress"}
$Domain = ‘tenant.mail.onmicrosoft.com’$Alias = ‘Malboxalias’$NewAddress = $Alias+’@’+$DomainSet-Mailbox $PrimarySMTP -EmailAddresses @{Add="$EmailAddress"}

3. Bad domain check

# Good Domains$GoodDomains = 'domain1.com','domain2.com','domain3.com','tenant.mail.onmicrosoft.com'$Mailboxes = Get-mailboxForeach ($Mailbox in $Mailboxes) {#Email Addresses to examine$Addresses = $Mailbox.EmailAddresses$User = $Mailbox.DisplayName$UPN = $Mailbox.UserPrincipalNameForeach ($Address in $Addresses) {$SmtpAddress = $Address.SMTPAddress$CurrentDomain = ($SMTPAddress.Split('@'))If ($GoodDomains -NotContains $CurrentDomain) {$output = "$User,$UPN,$CurrentDomain." | Out-File -File $LogDestination -Append}}}

Remediation

Any non-validated domain will stop a migration in its tracks, so how do we remove them? The easiest, and the most potentially destructive, is to do this:

$Aliases = (Get-Mailbox -ResultSize Unlimited |Where {$_.EmailAddresses -like "*baddomain.com"}).AliasForeach ($Alias in $Aliases){$EmailAddresses = (Get-Mailbox $Alias).EmailAddressesForeach ($EmailAddress in $EmailAddresses) {If ($EmailAddress -like "*baddomain.com"){Set-Mailbox $Alias -EmailAddresses @{remove="$EmailAddress"}}}}

This code block will identify any mailbox that has an SMTP Address with the ‘baddomain.com’ domain and then removes any address that matches that domain. Be careful as this can cause issues if you depend on that domain for something. It may be useful to filter this if only certain mailboxes need that domain removed.

4. Retention and Litigation Holds applied

$LitigationMailboxes = Get-Mailbox -Filter {LitigationHoldEnabled -eq $True} | Select-Object DisplayName,PrimarySMTPAddress | Out-File $LitigationDestination -Append$RetentionMailboxes = Get-Mailbox | Where {$_.RetentionHoldEnabled -eq $True} | Select-Object DisplayName,PrimarySMTPAddress | Out-File $RetentionDestination -Append
Get-Mailbox -ResultSize Unlimited | Get-MailboxFolderStatistics -IncludeAnalysis -FolderScope All | Where-Object {$_.TopSubjectSize -gt 125MB} | Select-Object Identity, TopSubject, TopSubjectSize | Export-CSV -path "C:reportsLArgeItemReport.csv" -notype

Monitoring Exchange Server

  • Submission: Messages waiting to be processed by transport agents
  • Unreachable: Messages that could not be delivered to their destination
  • Poison message: Messages classified as dangerous for the server.

To check the contents of the submission queue run the following command:

PS > Get-Queue -Identity Submission

1 PS>Get-Queue-Identity Submission

Exchange Server has some useful logs that you can check. Use the Get-MessageTrackingLog cmdlet to search for message delivery information stored in the message tracking log.

PS > Get-MessageTrackingLog -start » -resultsize unlimited | where-object {$_.Sender -like ‘*domain.com’}

1 PS>Get-MessageTrackingLog-start»-resultsize unlimited|where-object{$_.Sender-like’*domain.com’}

StarWind HyperConverged Appliance is a turnkey, entirely software-defined hyperconverged platform purpose-built for intensive virtualization workloads. Bringing the desired performance and reducing downtime, the solution can be deployed by organizations with limited budgets and IT team resources. Also, it requires only one onsite node to deliver HA for your applications that make the solution even more cost-efficient.
Find out more about StarWind HyperConverged Appliance

Внедрение Microsoft Exchange Server 2016

Exchange Server 2016 является достаточно сложным продуктом, и его внедрение, вопреки некоторых мнений, несколько сложнее, чем запуск setup.exe и нескольких нажатий кнопок «Далее». Развёртывание Exchange Server 2016 в масштабах предприятия с большим числом пользователей и большим количеством филиалов требует наличия сертифицированных специалистов с большим опытом участия в аналогичных проектах. Помимо разработки самой инфраструктуры серверов MS Exchange, требуется соответствующее планирование структуры домена Active Directory, топологии сайтов, т.к. работа Exchange напрямую зависит от функционирования контроллеров домена и серверов глобального каталога. При разработке отказоустойчивых кластерных конфигураций нужно учесть огромное количество факторов, влияющих на работоспособность почтовой системы. Т.к. создать систему, которая не имеет единой точки отказа – довольно не простая задача. И нужно понимать, что просто развёрнутый кластер Exchange Server 2016 – не есть панацея от всех проблем. Так, например, вы можете вложить несколько тысяч долларов в построение кластера Exchange, а вашу систему на сутки выведет из строя сгоревший коммутатор или ИБП. Именно по этим причинам компании возлагают задачи по развертыванию Microsoft Exchange Server на системных интеграторов. Но и здесь нужно не ошибиться, не все системные интеграторы могут качественно развернуть систему корпоративной почты на базе Exchange Server. Следует убедиться, что системный интегратор сертифицирован на выполнение данного вида работ, а также убедиться, что он имеет портфолио успешно завершённых аналогичных проектов.

Компания ЛанКей — сертифицированный системный интегратор, является золотым партнёром Microsoft (Microsoft Gold Certified Partner) и имеет золотую компетенцию Gold Messaging, что подтверждает наш наивысший опыт и профессионализм в области внедрения Exchange Server 2016. В проектах принимают участие сертифицированные Microsoft инженеры, обладающие статусами MCSE Messaging и MCITP Enterprise Messaging Administrators.

Компания ЛанКей также предлагает услуги по миграции на Exchange Server 2016 с предыдущих версий и других почтовых систем, таких как Novell GroupWise, IBM Lotus Notes или почтовых серверов на базе ОС Linux. Системный интегратор ЛанКей включает в себя департамент сервисного обслуживания, который в том числе оказывает услуги ИТ-аутсорсинга систем корпоративной почты на базе Exchange Server 2016. Компания ЛанКей готова обеспечить сопровождение, поддержку и обслуживание вашей корпоративной почтовой системы.

Понравилась статья? Поделиться с друзьями:
Быть в курсе нового
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: