C# で Exchange Online Remote PowerShell V2 Module を使用して Exchange Online へ接続する (.NET Framework 4.7.2 編)

更新日:

Important

この記事は 2021 年時点の手順です。Exchange Online の Remote PowerShell は廃止されており、この V2 Module を使用した接続方法は利用できません。詳しくは Remote PowerShell の廃止に関する Exchange Team Blog と、現在の Exchange Online PowerShell V3 Module のドキュメント を参照してください。以下のサンプルは当時の記録であり、パスワードをコードに埋め込まないでください。

他の実行環境向けの情報は以下から確認してください。

プログラムから Exchange へ PowerShell 接続する方法として、以下の技術情報が公開されています。

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

ただし、本記事の執筆時点ではこの技術情報の最終更新は 2015 年 9 月と非常に古く、更新が行われていません。また、ここで説明されている内容は参考にはなりますが、Remote Runspace に接続する方法になっています。Remote Runspace は、ざっくりとしたイメージとしては Exchange サーバーや Exchange Online のサーバー上でコマンドを実行させるものとなります。そのため、さまざまなセキュリティ上の制限を受けることになります。例えば変数や代入式の利用など、スクリプティングで一般的に使用されている構文が利用できません。

そのため、特に制限がない Local Runspace の使用が必要になりますが、その方法についてはサンプル コードが公開されていません。とはいえ、やることは Windows PowerShell で Exchange Online に接続する場合と同じです。従来の基本認証による接続であれば New-PSSession と Import-PSSession を行うことで Exchange Online のコマンドが Local Runspace にインポートされます。Exchange Online PowerShell V2 Module を利用する場合は、Connect-ExchangeOnline が内部で New-PSSession と Import-PSSession を行います。

ここでは、C# で Exchange Online Remote PowerShell V2 Module を使用して Exchange Online へ接続する方法を紹介します。Visual Studio の利用方法や C# でのアプリケーション開発方法を理解している方を対象としていますので、ステップ バイ ステップのような詳細な手順は記載していません。

環境

以下の環境で動作確認を行っています。

  • 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

今回は実行環境として .NET Framework 4.7.2 を想定しています。そのため PowerShell は .NET Framework で動作する Windows PowerShell 5.1 を使用します。PowerShell 7 などの .NET Core 環境で動作する PowerShell は利用できません。

前提条件

開発環境および本番環境で、ExchangeOnlineManagement PowerShell Module を使用した接続が既にできるようになっている必要があります。公開情報を参考に環境を用意してください。プログラムの実行アカウントと ExchangeOnlineManagement PowerShell Module をインストールするユーザーが違う場合は、モジュールを Install-Module コマンドの Scope パラメーターで AllUsers を指定してインストールしておく必要があります。

証明書を使用して接続を行うには、Exchange Online への PowerShell 接続を非対話的に行う方法などを参考に証明書を使用した接続ができるようになっている必要があります。

手順

  1. Visual Studio を起動して新しい C# のコンソール アプリケーションのプロジェクトを作成します。ターゲットのフレームワークは .NET Framework 4.7.2 にします。
  2. プロジェクトに NuGet で Microsoft.PowerShell.5.1.ReferenceAssemblies をインストールします。
  3. プロジェクトのプロパティから、対象プラットフォームを Any CPU から x64 に変更します。
  4. 以下の内容を参考に、コーディングします。
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. このコードには、Connect-ExchangeOnline が提供している以下の 4 つの方法が実装されています。V2ModuleExchangeOnlineRemotePowerShell 内の接続メソッドの呼び出しを、試したいもの 1 つ以外はコメント アウトします。
    • UPN とパスワードを使用する方法 (ConnectExchangeOnlineUsingUserPrinsipalNameAndPassword)
    • PFX ファイルを使用する方法 (ConnectExchangeOnlineUsingPfxFile)
    • 拇印を指定する方法 (ConnectExchangeOnlineUsingThumbprint)
    • X509Certificate2 のオブジェクトを指定する方法 (ConnectExchangeOnlineUsingX509Certificate2)
  2. デバッグ実行を開始します。正常に実行されると、Get-Mailbox の結果と Get-EXOMailbox の結果が表示されます。

補足解説

WriteStreams メソッドは、実行したコマンドのエラー出力、警告出力、情報出力をコンソールに書き出すものです。標準出力の書き出しが必要なものに関しては各コマンドごとに実装しています。

4 つの接続方法のメソッドには、それぞれ環境固有の情報が必要になっているので、実行環境に合わせてテナント名などの変数の内容を書き換える必要があります。

Connect-ExchangeOnline で IE のプロキシ設定を使用するように PSSessionOption を指定しています。プロキシ サーバーを使用しない環境では必ずしも必要な指定ではありません。トラブルシューティングで Fiddler トレースを採取する時には、この設定があれば Exchange Online への通信も Fiddler を経由するようにできます。

広告