最近工作中一個web項目需要集成exchange郵箱服務,注冊用戶時需要動態創建郵箱用戶,終於在http://www.cnblogs.com/gongguo/archive/2012/03/12/2392049.html中找到了解決方案。但在實現的過程中還是出現了些問題,經過幾次嘗試終於成功調用。
就自己碰到的問題記錄下來共勉。
直接用C#代碼訪問ExChange不會報錯,但不會成功創建郵箱用戶,主要是因為權限不足導致。
微軟出了一個PowerShell的命令行工具 能夠用命令行來操作ExChange,創建郵箱賬號的命令是 new-mailbox
可以通過把.Net類注冊成COM+組件的方式來操作PowerShell。
這里需要注意的是, 當你的調試環境和exchange服務器環境不一樣時(比如調試環境是win7 64,exchange服務器是winserver2008 64),將編譯的64位dll放在web項目里會報錯,此時你可以忽略這個錯誤,只有放到exchange服務器后才會成功,所以最好調試環境和exchange服務器一致。
轉==============================================================================
我的流程就是
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)拷貝下面的方法到類中

#region 根據登錄名判斷是否存在郵箱 public bool IsExistMailBox(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Get-Mailbox"); command.Parameters.Add("identity", identity); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return (result != null && result.Count > 0); } catch (System.Exception ex) { throw ex; } } #endregion #region 創建郵箱賬號 public bool NewMailbox(string name, string accountName, string pwd, string emailDomain, string organizationalUnit, string database) { string emailAdd = accountName + emailDomain; if (this.IsExistMailBox(emailAdd)) { throw new Exception("已經存在同名的郵箱"); } try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("New-Mailbox"); char[] passwordChars = pwd.ToCharArray(); SecureString password = new SecureString(); foreach (char c in passwordChars) { password.AppendChar(c); } command.Parameters.Add("Name", name);//姓名 command.Parameters.Add("UserPrincipalName", emailAdd);//郵箱地址 command.Parameters.Add("SamAccountName", accountName);//登錄名 command.Parameters.Add("Password", password);//密碼 command.Parameters.Add("OrganizationalUnit", organizationalUnit);//組織單元 command.Parameters.Add("Database", database);//數據庫 pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return this.IsExistMailBox(emailAdd); } catch (Exception ex) { throw ex; } } #endregion #region 刪除郵箱賬號(控制台和域都刪除) public bool RemoveMailbox(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Remove-Mailbox"); command.Parameters.Add("Identity", identity); command.Parameters.Add("Confirm", false); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return !this.IsExistMailBox(identity); } catch (System.Exception ex) { throw ex; } } #endregion #region 啟用郵箱賬號 public bool EnableMailbox(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Enable-Mailbox"); command.Parameters.Add("Identity", identity); command.Parameters.Add("Confirm", false); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return this.IsExistMailBox(identity); } catch (Exception ex) { throw ex; } } #endregion #region 禁用郵箱賬號 public bool DisableMailbox(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Disable-Mailbox"); command.Parameters.Add("Identity", identity); command.Parameters.Add("Confirm", false); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return !this.IsExistMailBox(identity); } catch (Exception ex) { throw ex; } } #endregion #region 判斷是否存在通訊組 public bool IsExistGroup(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Get-DistributionGroup"); command.Parameters.Add("identity", identity); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return (result != null && result.Count > 0); } catch (System.Exception ex) { throw ex; } } #endregion #region 創建通訊組 public bool NewGroup(string name) { if (this.IsExistGroup(name)) { throw new Exception("已經存在相同的通訊組"); } try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("New-DistributionGroup"); command.Parameters.Add("Name", name); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return this.IsExistGroup(name); } catch (Exception ex) { throw ex; } } #endregion #region 刪除通訊組 public bool RemoveGroup(string identity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Remove-DistributionGroup"); command.Parameters.Add("Identity", identity); command.Parameters.Add("Confirm", false); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return !this.IsExistGroup(identity); } catch (Exception ex) { throw ex; } } #endregion #region 添加通訊組成員 public bool AddGroupMember(string groupIdentity, string mailIdentity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Add-DistributionGroupMember"); command.Parameters.Add("Identity", groupIdentity); command.Parameters.Add("Member", mailIdentity); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return true; } catch (Exception ex) { throw ex; } } #endregion #region 刪除通訊組成員 public bool RemoveGroupMember(string groupIdentity, string mailIdentity) { try { PSSnapInException PSException = null; RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create(); runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command("Remove-DistributionGroupMember"); command.Parameters.Add("Identity", groupIdentity); command.Parameters.Add("Member", mailIdentity); command.Parameters.Add("Confirm", false); pipeline.Commands.Add(command); Collection<PSObject> result = pipeline.Invoke(); runspace.Close(); return true; } catch (Exception ex) { throw ex; } } #endregion
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);