Exchange2010與Exchange2007不同,除了邊緣傳輸服務器可以使用本地命令管理程序,要使用遠程命令管理程序,否則無法使用Exchange2010裏的cmdlet。
using System
using System.Management.Automation; //---直接在csproj文件中添加引用<Reference Include="System.Management.Automation" />
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Security;
//---管理員的密碼
String admin_pwd = "XXXXXXXXXXX";
char[] admin_pwd_Chars = admin_pwd.ToCharArray();
SecureString admin_pwd_s = new SecureString();
foreach (char c in admin_pwd_Chars)
{ admin_pwd_s.AppendChar(c); }
//--設置憑據
PSCredential pCredential = new PSCredential("administrator", admin_pwd_s);
//-- 遠程連接,xxx.com.cn爲Exchange2010服務器地址
WSManConnectionInfo pConnectionInfo = new WSManConnectionInfo(new Uri("http://xxx.com.cn/PowerShell"), "http://schemas.microsoft.com/PowerShell/Microsoft.Exchange", pCredential);
//-- 建立遠程 runspace
Runspace runspace = RunspaceFactory.CreateRunspace(pConnectionInfo);
下面是使用get-mailbox命令檢查test1帳戶信息,驗證通過。
string sScript = "get-mailbox -identity 'test1'";
pipline.Commands.AddScript(sScript);
try
{ Collection<PSObject> results = pipline.Invoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{ stringBuilder.AppendLine(obj.ToString()); }
MessageBox.Show(stringBuilder.ToString());
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
pipline.Dispose();
runspace.Close();
}