实现过程在工作中经常会通过执行power shell命令来完成一系列操作,在.net中也可以直接调用power shell命令,具体过程如下
1、所需dll
Microsoft.Exchange.WebServices 15.0.0.0
System.Management.Automation 3.0.0.0
2、配置文件
3、完整代码
此代码执行的power shell命令为如下,作用是为了解决问题:The specified folder could not be found in the store
Add-MailboxPermission -Identity “liuzhenhe@oms.com” -User "administrator@oms.com" -AccessRights FullAccess
////// 运行power shell命令 /// /// ///public string runPowerShell(string user) { string errorMsg = ""; string url = ConfigurationManager.AppSettings["SYS.Exchange.URI"]; string username = ConfigurationManager.AppSettings["SYS.Exchange.Name"]; string pwd = ConfigurationManager.AppSettings["SYS.Exchange.Password"]; System.Security.SecureString password = new System.Security.SecureString(); foreach (char x in pwd) { password.AppendChar(x); } string liveIdconnectionUri = url; PSCredential credential = new PSCredential(username, password); WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential); connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos; { Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo); runspace.Open(); try { PowerShell ps = PowerShell.Create(); PSCommand command = new PSCommand(); command.AddCommand("Add-MailboxPermission"); command.AddParameter("Identity", user); command.AddParameter("User", "administrator@oms.com"); command.AddParameter("AccessRights", "FullAccess"); ps.Commands = command; ps.Runspace = runspace; Collection results = ps.Invoke(); if (ps.HadErrors) { errorMsg = "Enable-Mailbox ERROR:"; if (ps.Streams.Error.Count > 0) { for (int i = 0; i < ps.Streams.Error.Count; i++) { errorMsg += ps.Streams.Error[i].Exception.ToString(); } } } else { errorMsg = ""; } } catch (Exception ex) { errorMsg = "Enable-Mailbox ERROR:"; if (ex.InnerException != null && ex.InnerException.Message != null) { errorMsg += ex.InnerException.Message; } else { errorMsg += ex.ToString(); } } finally { runspace.Dispose(); runspace = null; } return errorMsg; } }



