.NET通過PowerShell操作ExChange為用戶開通郵箱教程


最近在工作中負責解決 用代碼在Exchange中為用戶創建郵箱 的問題

主要就是用C#封裝一個ExChange操作類,在ExChange的服務器上發布一個WebService  供系統的java代碼調用


在查閱很多資料后,終於在

http://www.cnblogs.com/xiaogelove/archive/2011/02/17/1956617.html

這篇帖子的指導下把這個問題解決了

不過這個帖子講得並不是特別的詳細

所以我覺得有必要把我在這個過程中遇到的問題記錄下來

所以在上面這篇帖子的基礎上寫了一個相對詳細的新流程


==============================================================================

主要原理是:(這個原理是我猜的,因為我也不太懂ExChange以及COM組件這方面的知識) 

直接用C#代碼訪問ExChange是不行的

微軟出了一個PowerShell的命令行工具 能夠用命令行來操作ExChange

可以通過把.Net類注冊成COM+組件的方式來操作PowerShell


所以我的流程就是

WebService->.NET寫的PowerShell操作類注冊成的COM+組件->ExChange

環境是:

VS2010 + ExChange2010 + Windows Server 2008 64位版 + IIS7.0 


ps:這個COM+組件只能運行在安裝ExChange的服務器上

公司的環境用的是ExChange2010, ExChange2010好像只有64位版的 只能安裝在64位的系統上

所以下面會說到把COM+組件編譯成64位的問題

==============================================================================


1 首先先創建com組件並注冊

1)啟動Visual Studio 2010

2)選擇File ->“新建->”項目...

3)選擇Windows

4)選擇類庫

5)在名稱框中鍵入“PowerShellComponent “

6)點擊確定。

7)添加下列引用

System.EnterpriseServices

System.DirectoryServices

System.Management.Automation 路徑:

32位系統:

C:\ProgramFiles\ReferenceAssemblies\Microsoft\WindowsPowerShell\v1.\System.Management.Automation.dll

64位系統

C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll


接下來有關程序集的操作

1)在解決方案資源管理器,右鍵單擊PowerShellComponent項目,選擇屬性,點擊簽名選項,選中"為程序集簽名",並創建一個新的強名稱密鑰稱為“PowerShellComponent.snk”  不用設置密碼。如下圖

 

 

 

2)還是在項目屬性窗口中,選擇"應用程序"選項卡,然后點擊“程序集信息...”,檢查框,選中"使程序集COM可見"。如圖

 

 

PS:如果運行這個com組件的機器是64位系統(32位的沒試過),這里需要再加一步:

把項目的運行平台設置成64位

還是在項目屬性窗口中:

"生成"選項卡->目標平台->64位

    ->   


 

3)打開AssemblyInfo.cs中,並添加“using System.EnterpriseServices;”,並添加

 

[assembly: ApplicationActivation(ActivationOption.Server)] 
[assembly: ApplicationName("PowerShellComponent")] 
[assembly: Description("Simple PowerShell Component Sample")] 
[assembly: ApplicationAccessControl( 
           false, 
           AccessChecksLevel = AccessChecksLevelOption.Application, 
           Authentication = AuthenticationOption.None, 
           ImpersonationLevel = ImpersonationLevelOption.Identify)]

然后添加ManagementCommands類...

1)選擇“解決方案資源管理器”查看選項卡。將Class1.cs文件重命名為“ManagementCommands.cs”。

類需要繼承System.EnterpriseServices.ServicedComponent,否則不能被編譯成COM+組件

2)添加引用如圖並using

using System.EnterpriseServices;
using System.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.DirectoryServices;
using Microsoft.PowerShell.Commands;
using System.Collections;

3)拷貝下面的方法到類中

    

View Code
  1  #region 根據登錄名判斷是否存在郵箱
2
3 public bool IsExistMailBox(string identity)
4
5 {
6
7 try
8
9 {
10
11 PSSnapInException PSException = null;
12
13 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
14
15 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
16
17 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
18
19 runspace.Open();
20
21
22
23 Pipeline pipeline = runspace.CreatePipeline();
24
25 Command command = new Command("Get-Mailbox");
26
27 command.Parameters.Add("identity", identity);
28
29 pipeline.Commands.Add(command);
30
31 Collection<PSObject> result = pipeline.Invoke();
32
33
34
35 runspace.Close();
36
37
38
39 return (result != null && result.Count > 0);
40
41 }
42
43 catch (System.Exception ex)
44
45 {
46
47 throw ex;
48
49 }
50
51 }
52
53 #endregion
54
55
56
57 #region 創建郵箱賬號
58
59 public bool NewMailbox(string name, string accountName, string pwd, string emailDomain, string organizationalUnit, string database)
60
61 {
62
63 string emailAdd = accountName + emailDomain;
64
65
66
67 if (this.IsExistMailBox(emailAdd))
68
69 {
70
71 throw new Exception("已經存在同名的郵箱");
72
73 }
74
75 try
76
77 {
78
79 PSSnapInException PSException = null;
80
81 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
82
83 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
84
85 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
86
87 runspace.Open();
88
89 Pipeline pipeline = runspace.CreatePipeline();
90
91
92
93 Command command = new Command("New-Mailbox");
94
95 char[] passwordChars = pwd.ToCharArray();
96
97 SecureString password = new SecureString();
98
99 foreach (char c in passwordChars)
100
101 {
102
103 password.AppendChar(c);
104
105 }
106
107
108
109 command.Parameters.Add("Name", name);//姓名
110
111
112
113 command.Parameters.Add("UserPrincipalName", emailAdd);//郵箱地址
114
115 command.Parameters.Add("SamAccountName", accountName);//登錄名
116
117
118
119 command.Parameters.Add("Password", password);//密碼
120
121
122
123 command.Parameters.Add("OrganizationalUnit", organizationalUnit);//組織單元
124
125 command.Parameters.Add("Database", database);//數據庫
126
127
128
129 pipeline.Commands.Add(command);
130
131 Collection<PSObject> result = pipeline.Invoke();
132
133 runspace.Close();
134
135
136
137 return this.IsExistMailBox(emailAdd);
138
139 }
140
141 catch (Exception ex)
142
143 {
144
145 throw ex;
146
147 }
148
149 }
150
151 #endregion
152
153
154
155 #region 刪除郵箱賬號(控制台和域都刪除)
156
157
158
159 public bool RemoveMailbox(string identity)
160
161 {
162
163
164
165 try
166
167 {
168
169 PSSnapInException PSException = null;
170
171 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
172
173 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
174
175 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
176
177 runspace.Open();
178
179 Pipeline pipeline = runspace.CreatePipeline();
180
181
182
183 Command command = new Command("Remove-Mailbox");
184
185 command.Parameters.Add("Identity", identity);
186
187 command.Parameters.Add("Confirm", false);
188
189 pipeline.Commands.Add(command);
190
191 Collection<PSObject> result = pipeline.Invoke();
192
193 runspace.Close();
194
195
196
197 return !this.IsExistMailBox(identity);
198
199 }
200
201 catch (System.Exception ex)
202
203 {
204
205 throw ex;
206
207 }
208
209 }
210
211 #endregion
212
213
214
215 #region 啟用郵箱賬號
216
217 public bool EnableMailbox(string identity)
218
219 {
220
221 try
222
223 {
224
225 PSSnapInException PSException = null;
226
227 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
228
229 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
230
231 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
232
233 runspace.Open();
234
235 Pipeline pipeline = runspace.CreatePipeline();
236
237
238
239 Command command = new Command("Enable-Mailbox");
240
241 command.Parameters.Add("Identity", identity);
242
243 command.Parameters.Add("Confirm", false);
244
245 pipeline.Commands.Add(command);
246
247 Collection<PSObject> result = pipeline.Invoke();
248
249 runspace.Close();
250
251 return this.IsExistMailBox(identity);
252
253 }
254
255 catch (Exception ex)
256
257 {
258
259 throw ex;
260
261 }
262
263 }
264
265 #endregion
266
267
268
269 #region 禁用郵箱賬號
270
271 public bool DisableMailbox(string identity)
272
273 {
274
275 try
276
277 {
278
279 PSSnapInException PSException = null;
280
281 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
282
283 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
284
285 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
286
287 runspace.Open();
288
289
290
291 Pipeline pipeline = runspace.CreatePipeline();
292
293 Command command = new Command("Disable-Mailbox");
294
295 command.Parameters.Add("Identity", identity);
296
297 command.Parameters.Add("Confirm", false);
298
299 pipeline.Commands.Add(command);
300
301 Collection<PSObject> result = pipeline.Invoke();
302
303 runspace.Close();
304
305 return !this.IsExistMailBox(identity);
306
307 }
308
309 catch (Exception ex)
310
311 {
312
313 throw ex;
314
315 }
316
317 }
318
319 #endregion
320
321
322
323 #region 判斷是否存在通訊組
324
325 public bool IsExistGroup(string identity)
326
327 {
328
329 try
330
331 {
332
333 PSSnapInException PSException = null;
334
335 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
336
337 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
338
339 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
340
341 runspace.Open();
342
343
344
345 Pipeline pipeline = runspace.CreatePipeline();
346
347 Command command = new Command("Get-DistributionGroup");
348
349 command.Parameters.Add("identity", identity);
350
351 pipeline.Commands.Add(command);
352
353 Collection<PSObject> result = pipeline.Invoke();
354
355
356
357 runspace.Close();
358
359
360
361 return (result != null && result.Count > 0);
362
363 }
364
365 catch (System.Exception ex)
366
367 {
368
369 throw ex;
370
371 }
372
373 }
374
375 #endregion
376
377
378
379 #region 創建通訊組
380
381 public bool NewGroup(string name)
382
383 {
384
385 if (this.IsExistGroup(name))
386
387 {
388
389 throw new Exception("已經存在相同的通訊組");
390
391 }
392
393 try
394
395 {
396
397 PSSnapInException PSException = null;
398
399 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
400
401 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
402
403 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
404
405 runspace.Open();
406
407
408
409 Pipeline pipeline = runspace.CreatePipeline();
410
411 Command command = new Command("New-DistributionGroup");
412
413 command.Parameters.Add("Name", name);
414
415 pipeline.Commands.Add(command);
416
417 Collection<PSObject> result = pipeline.Invoke();
418
419 runspace.Close();
420
421 return this.IsExistGroup(name);
422
423 }
424
425 catch (Exception ex)
426
427 {
428
429 throw ex;
430
431 }
432
433 }
434
435
436
437 #endregion
438
439
440
441 #region 刪除通訊組
442
443 public bool RemoveGroup(string identity)
444
445 {
446
447 try
448
449 {
450
451 PSSnapInException PSException = null;
452
453 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
454
455 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
456
457 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
458
459 runspace.Open();
460
461
462
463 Pipeline pipeline = runspace.CreatePipeline();
464
465 Command command = new Command("Remove-DistributionGroup");
466
467 command.Parameters.Add("Identity", identity);
468
469 command.Parameters.Add("Confirm", false);
470
471 pipeline.Commands.Add(command);
472
473 Collection<PSObject> result = pipeline.Invoke();
474
475 runspace.Close();
476
477 return !this.IsExistGroup(identity);
478
479 }
480
481 catch (Exception ex)
482
483 {
484
485 throw ex;
486
487 }
488
489 }
490
491 #endregion
492
493
494
495 #region 添加通訊組成員
496
497 public bool AddGroupMember(string groupIdentity, string mailIdentity)
498
499 {
500
501 try
502
503 {
504
505 PSSnapInException PSException = null;
506
507 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
508
509 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
510
511 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
512
513 runspace.Open();
514
515
516
517 Pipeline pipeline = runspace.CreatePipeline();
518
519 Command command = new Command("Add-DistributionGroupMember");
520
521 command.Parameters.Add("Identity", groupIdentity);
522
523 command.Parameters.Add("Member", mailIdentity);
524
525 pipeline.Commands.Add(command);
526
527 Collection<PSObject> result = pipeline.Invoke();
528
529 runspace.Close();
530
531 return true;
532
533 }
534
535 catch (Exception ex)
536
537 {
538
539 throw ex;
540
541 }
542
543 }
544
545 #endregion
546
547
548
549 #region 刪除通訊組成員
550
551 public bool RemoveGroupMember(string groupIdentity, string mailIdentity)
552
553 {
554
555 try
556
557 {
558
559 PSSnapInException PSException = null;
560
561 RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
562
563 runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
564
565 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
566
567 runspace.Open();
568
569
570
571 Pipeline pipeline = runspace.CreatePipeline();
572
573 Command command = new Command("Remove-DistributionGroupMember");
574
575 command.Parameters.Add("Identity", groupIdentity);
576
577 command.Parameters.Add("Member", mailIdentity);
578
579 command.Parameters.Add("Confirm", false);
580
581 pipeline.Commands.Add(command);
582
583 Collection<PSObject> result = pipeline.Invoke();
584
585 runspace.Close();
586
587 return true;
588
589 }
590
591 catch (Exception ex)
592
593 {
594
595 throw ex;
596
597 }
598
599 }
600
601 #endregion
602
603

 

       

PS: 這些都是ExChange的命令,暫時只封裝了這么多,如果想實現更多的功能,只需要照着上面的例子把實現相應的ExChange命令就行了

在微軟的官網上有ExChange的命令文檔 http://msdn.microsoft.com/zh-cn/library/aa997174.aspx

 

最后運行生成項目,得到PowerShellComponent.dll,COM組件就創建好了。

接下來就是注冊這個組件了:  

步驟一:
【控制面板】→【管理工具】→【組件服務】

 

 步驟二:
出現窗口后,【組件服務】→【計算機】→【我的電腦】→【COM+ 應用程序】單擊右鍵 →新建→ 應用程序→安裝向導下一步→創建空應用程序→輸入空應用程序名稱:PowerShellComponent,並選擇激活類型為服務器應用程序→設置應用程序標示(賬號選擇下列用戶 賬號和密碼是該服務器登錄用戶名和密碼)→完成。

右鍵單擊創建出來的PowerShellComoponent,選擇屬性,找到"標志"選項卡,選擇 ”下列用戶“ 填入計算機的登錄用戶名和密碼,確定 

 

 步驟三:
創建好應用程序后 打開PowerShellComponent 出現 【組件】【舊版組件】【角色】 在【組件】上單擊右鍵  →新建→組件 


 步驟三:
點下一步,出現如下窗口,選擇【安裝新組件】:



選擇前面項目生成的PowerShellComponent.dll文件→【打開】點下一步,選擇完成。

 步驟四:

為剛剛注冊的PowerShellComponent組件添加用戶權限

打開PowerShellComponent 下面的【角色】-【CreatorOwner】-【用戶】右鍵  【新建】 - 【用戶】

 


在出來的窗口點[高級]-[位置]-選擇[整個目錄]-[立即查找]

 


因為WebServicce是發布在IIS上面的 所以我的IIS需要有權限來操作這個COM組件 所以我添加的是IIS的用戶

在搜索出來的結果里面 選擇IIS_IUSRS並添加,  如果是用winform來調用這個COM+組件 則應該要添加管理員帳號Administrator

 


用戶添加完了  組件就注冊成功了。

把PowerShellComponent.dll拷到測試項目中 

測試項目添加對 PowerShellComponent.dll 的引用   就能被調用了

  

如果你的COM+組件被啟用了 在調試過程中如果你需要重新編譯你的DLL文件 那么需要先關閉COM+組件  dll才能被重新編譯

如果在調用的過程中發生異常,可能是兩個方面的原因:

1  如果com+組件在64位的環境下運行 是否有被編譯成64位

2 權限問題

 

還有一個 

因為操作的是ExChange2010  所以代碼中是

 

PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);



如果你的ExChange是2007的  那么這行代碼可能需要被改成

 

PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out PSException);


http://ishare.iask.sina.com.cn/f/23481273.html

這是我的源代碼,賺點積分,勿怪


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM