Warning
Exchange Server 2019 is no longer supported. See Microsoft’s lifecycle information for support dates and migration guidance.
The following technical article describes how to connect to Exchange using PowerShell from a program:
Get a list of mail users by using the Exchange Management Shell
However, when this blog post was written, the article did not describe how to connect to Exchange Server 2019 by using the Microsoft.Exchange.Management.PowerShell.RecipientManagement snap-in for managing on-premises recipients in an Exchange hybrid environment.
The basic steps are the same as when you use Windows PowerShell.
This article explains how to connect to Exchange Server 2019 from C# by using a snap-in in the Exchange Management Tools. It is intended for readers who are familiar with Visual Studio and C# application development, so it does not provide step-by-step instructions for those topics.
Environment
The following environment was tested:
- Visual Studio 2022
- .NET Framework 4.8
- Windows PowerShell 5.1
- Exchange Server 2019 CU14
- Microsoft.PowerShell.5.1.ReferenceAssemblies 1.0.0
Exchange Server 2019 requires .NET Framework 4.8. Therefore, this example uses Windows PowerShell 5.1, which runs on .NET Framework. It cannot use PowerShell that runs in a .NET Core environment, such as PowerShell 7.
Prerequisites
You must be able to manage Exchange Server with the Microsoft.Exchange.Management.PowerShell.RecipientManagement snap-in in both your development and production environments. See Manage recipients in Exchange hybrid environments using the management tools to prepare your environment.
Steps
- In Visual Studio, create a new C# Console Application project. Set the target framework to .NET Framework 4.8.
- Install
Microsoft.PowerShell.5.1.ReferenceAssembliesin the project from NuGet. - In the project properties, change the target platform from
Any CPUtox64. - Use the following code as a reference:
1 | using System; |
- Start debugging. If it runs successfully, the results of
Get-RemoteMailboxare displayed.
Additional explanation
The WriteStreams method writes the error, warning, and information streams from the commands to the console. Output that needs to be written to standard output is implemented for each command.