Connect to Exchange Online with the Remote PowerShell V2 Module in C# (.NET Framework 4.7.2)

Updated:

Important

This article records procedures from 2021. Remote PowerShell for Exchange Online has been retired, so the connection method using this V2 module is no longer available. See the Exchange Team Blog on Remote PowerShell retirement and the current Exchange Online PowerShell V3 module documentation. The sample below is a historical record; do not embed passwords in code.

For other runtime environments, see:

The following documentation describes how to connect to Exchange with PowerShell from a program:

Get a list of mail users by using the Exchange Management Shell

At the time of writing, this documentation had not been updated since September 2015. Although it is useful as a reference, it describes a connection to a remote runspace. In simple terms, a remote runspace runs commands on an Exchange server or an Exchange Online server. It is therefore subject to various security restrictions. For example, common scripting syntax such as variables and assignment expressions is not available.

A local runspace, which does not have those restrictions, is needed instead, but no sample code for this approach has been published. The steps are nevertheless the same as when connecting to Exchange Online from Windows PowerShell. With the traditional Basic authentication connection, New-PSSession and Import-PSSession import the Exchange Online commands into the local runspace. When using the Exchange Online PowerShell V2 module, Connect-ExchangeOnline runs New-PSSession and Import-PSSession internally.

This article explains how to connect to Exchange Online from C# using the Exchange Online Remote PowerShell V2 module. It assumes familiarity with Visual Studio and C# application development, so it does not provide detailed step-by-step instructions.

Environment

The sample was tested in the following environment:

  • Visual Studio 2019
  • .NET Framework 4.7.2
  • Windows PowerShell 5.1
  • ExchangeOnlineManagement PowerShell Module 2.0.5
  • Microsoft.PowerShell.5.1.ReferenceAssemblies 1.0.0

The runtime environment is .NET Framework 4.7.2, so the sample uses Windows PowerShell 5.1, which runs on .NET Framework. PowerShell running on .NET Core, such as PowerShell 7, cannot be used in this environment.

Prerequisites

Both the development and production environments must already be configured to connect using the ExchangeOnlineManagement PowerShell module. Refer to the documentation to prepare the environment. If the account running the program differs from the user installing the module, install it with the Install-Module command’s Scope parameter set to AllUsers.

To connect using a certificate, first configure certificate-based connections by following, for example, Connect to Exchange Online PowerShell non-interactively.

Steps

  1. Start Visual Studio and create a new C# console application project targeting .NET Framework 4.7.2.
  2. Install Microsoft.PowerShell.5.1.ReferenceAssemblies in the project using NuGet.
  3. In the project properties, change the target platform from Any CPU to x64.
  4. Use the following code as a reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace ExchangeOnlinePowerShellNetFramework
{
class Program
{
static void Main(string[] args)
{
// Connect Exchange Online PowerShell using V2 module.
// ExchangeOnlineManagement PowerShell module need to be installed.
// Application need to be built as x64 app.

// If you don't know which PowerShell Nuget Packages you should use, read this blog.
// https://devblogs.microsoft.com/powershell/depending-on-the-right-powershell-nuget-package-in-your-net-project/
// You need to install Microsoft.PowerShell.5.1.ReferenceAssemblies when you use Windows PowerShell 5.1.

V2ModuleExchangeOnlineRemotePowerShell();

Console.ReadLine();
}

public static void WriteStreams(PSDataStreams Streams)
{
// Write Error, Warning and Information stream

PSDataCollection<ErrorRecord> errorStream = Streams.Error;
foreach (ErrorRecord errorRecord in errorStream)
{
Console.WriteLine(errorRecord.ToString());
}

PSDataCollection<WarningRecord> warningRecords = Streams.Warning;
foreach (WarningRecord warningRecord in warningRecords)
{
Console.WriteLine(warningRecord.ToString());
}

PSDataCollection<InformationRecord> informationRecords = Streams.Information;
foreach (InformationRecord informationRecord in informationRecords)
{
Console.WriteLine(informationRecord.ToString());
}

Console.WriteLine("");
}

public static void ConnectExchangeOnlineUsingUserPrinsipalNameAndPassword(Runspace runspace)
{
// Connect to Exchange Online using UPN and password

using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Connect-ExchangeOnline -Credential <Cred> -ShowProgress $false -ShowBanner $false");

string userPrincipalName = "admin@contoso.onmicrosoft.com";
string password = "pass";

SecureString secureString = new SecureString();

foreach (var ch in password)
{
secureString.AppendChar(ch);
}

PSCredential pSCredential = new PSCredential(userPrincipalName, secureString);

shell.Runspace = runspace;
shell.Commands.AddCommand("Connect-ExchangeOnline");
shell.Commands.AddParameter("Credential", pSCredential);
shell.Commands.AddParameter("ShowProgress", false);
shell.Commands.AddParameter("ShowBanner", false);
shell.Commands.AddParameter("PSSessionOption", new PSSessionOption() { ProxyAccessType = ProxyAccessType.IEConfig });

shell.Invoke();

WriteStreams(shell.Streams);
}
}

public static void ConnectExchangeOnlineUsingPfxFile(Runspace runspace)
{
// Connect to Exchange Online using PFX file

using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Connect-ExchangeOnline -CertificateFilePath <PFX file> -CertificatePassword <Password> -AppID <App ID> -Organization <Tenant> -ShowProgress $false -ShowBanner $false");

string pfxFilePath = @"c:\temp\mycert.pfx";
string pfxFilePassword = "1234";
string appId = "7ffc8551-ac13-4fbc-b045-c57e9a9f2fbe";
string tenant = "contoso.onmicrosoft.com";

SecureString secureString = new SecureString();

foreach (var ch in pfxFilePassword)
{
secureString.AppendChar(ch);
}

shell.Runspace = runspace;
shell.Commands.AddCommand("Connect-ExchangeOnline");
shell.Commands.AddParameter("CertificateFilePath", pfxFilePath);
shell.Commands.AddParameter("CertificatePassword", secureString);
shell.Commands.AddParameter("AppID", appId);
shell.Commands.AddParameter("Organization", tenant);
shell.Commands.AddParameter("ShowProgress", false);
shell.Commands.AddParameter("ShowBanner", false);
shell.Commands.AddParameter("PSSessionOption", new PSSessionOption() { ProxyAccessType = ProxyAccessType.IEConfig });

shell.Invoke();

WriteStreams(shell.Streams);
}
}

public static void ConnectExchangeOnlineUsingThumbprint(Runspace runspace)
{
// Connect to Exchange Online using thumbprint

using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Connect-ExchangeOnline -CertificateThumbPrint <Thumbprint> -AppID <App ID> -Organization <Tenant> -ShowProgress $false -ShowBanner $false");

string certificateThumbPrint = "29F54F053F87ABBB0301FB51D002261AE217D85E";
string appId = "7ffc8551-ac13-4fbc-b045-c57e9a9f2fbe";
string tenant = "contoso.onmicrosoft.com";

shell.Runspace = runspace;
shell.Commands.AddCommand("Connect-ExchangeOnline");
shell.Commands.AddParameter("CertificateThumbPrint", certificateThumbPrint);
shell.Commands.AddParameter("AppID", appId);
shell.Commands.AddParameter("Organization", tenant);
shell.Commands.AddParameter("ShowProgress", false);
shell.Commands.AddParameter("ShowBanner", false);
shell.Commands.AddParameter("PSSessionOption", new PSSessionOption() { ProxyAccessType = ProxyAccessType.IEConfig });

shell.Invoke();

WriteStreams(shell.Streams);
}
}

public static void ConnectExchangeOnlineUsingX509Certificate2(Runspace runspace)
{
// Connect to Exchange Online using X509Certificate2

using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Connect-ExchangeOnline -Certificate <Cert> -AppID <App ID> -Organization <Tenant> -ShowProgress $false -ShowBanner $false");

string certificateThumbPrint = "29F54F053F87ABBB0301FB51D002261AE217D85E";
string appId = "7ffc8551-ac13-4fbc-b045-c57e9a9f2fbe";
string tenant = "contoso.onmicrosoft.com";

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var collection = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbPrint, false);
X509Certificate2 x509Certificate2 = collection[0];
store.Close();

shell.Runspace = runspace;
shell.Commands.AddCommand("Connect-ExchangeOnline");
shell.Commands.AddParameter("Certificate", x509Certificate2);
shell.Commands.AddParameter("AppID", appId);
shell.Commands.AddParameter("Organization", tenant);
shell.Commands.AddParameter("ShowProgress", false);
shell.Commands.AddParameter("ShowBanner", false);
shell.Commands.AddParameter("PSSessionOption", new PSSessionOption() { ProxyAccessType = ProxyAccessType.IEConfig });

shell.Invoke();

WriteStreams(shell.Streams);
}
}

public static void V2ModuleExchangeOnlineRemotePowerShell()
{
Collection<PSObject> results;

using (Runspace runspace = RunspaceFactory.CreateRunspace(RunspaceConfiguration.Create()))
{
// Open local runspace
runspace.Open();

// Load Exchange Online PowerShell V2 module
using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Import-Module ExchangeOnlineManagement");

shell.Runspace = runspace;
shell.Commands.AddScript("Import-Module ExchangeOnlineManagement");
shell.Invoke();

WriteStreams(shell.Streams);
}

// Connect to Exchange Online
//ConnectExchangeOnlineUsingUserPrinsipalNameAndPassword(runspace);
//ConnectExchangeOnlineUsingPfxFile(runspace);
//ConnectExchangeOnlineUsingThumbprint(runspace);
ConnectExchangeOnlineUsingX509Certificate2(runspace);

// Run Get-Mailbox
using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Get-Mailbox -ResultSize Unlimited");

shell.Runspace = runspace;
shell.AddScript("Get-Mailbox -ResultSize Unlimited");

results = shell.Invoke();

foreach (PSObject result in results)
{
Console.WriteLine(result.Properties["UserPrincipalName"].Value.ToString());
}

WriteStreams(shell.Streams);
}

// Run Get-EXOMailbox
using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Get-EXOMailbox -PropertySets Minimum -ResultSize Unlimited");

shell.Runspace = runspace;
shell.AddScript("Get-EXOMailbox -PropertySets Minimum -ResultSize Unlimited");

results = shell.Invoke();
foreach (PSObject result in results)
{
Console.WriteLine(result.Properties["UserPrincipalName"].Value.ToString());
}

WriteStreams(shell.Streams);
}

// Disconnect from Exchange Online
using (PowerShell shell = PowerShell.Create())
{
Console.WriteLine("Running : Disconnect-ExchangeOnline -Confirm:$false");

shell.Runspace = runspace;
shell.AddScript("Disconnect-ExchangeOnline -Confirm:$false");

results = shell.Invoke();
foreach (PSObject result in results)
{
Console.WriteLine(result.Properties["UserPrincipalName"].Value.ToString());
}

WriteStreams(shell.Streams);
}
}
}
}
}
  1. The code implements the following four methods provided by Connect-ExchangeOnline. In V2ModuleExchangeOnlineRemotePowerShell, comment out all but the connection method you want to try:
    • UPN and password (ConnectExchangeOnlineUsingUserPrinsipalNameAndPassword)
    • PFX file (ConnectExchangeOnlineUsingPfxFile)
    • Certificate thumbprint (ConnectExchangeOnlineUsingThumbprint)
    • X509Certificate2 object (ConnectExchangeOnlineUsingX509Certificate2)
  2. Start debugging. If it runs successfully, the results of Get-Mailbox and Get-EXOMailbox are displayed.

Additional explanation

The WriteStreams method writes the executed command’s error, warning, and information streams to the console. Standard output is written separately for each command where needed.

Each of the four connection methods requires environment-specific information. Change the variables, such as the tenant name, to match your environment.

The sample specifies PSSessionOption so that Connect-ExchangeOnline uses the IE proxy settings. This setting is not necessarily required in an environment without a proxy server. When collecting a Fiddler trace for troubleshooting, it allows Exchange Online traffic to go through Fiddler as well.

Advertisement