前几天,原来公司的一个小妹,发来求助MSN,说公司的EXCHNAGE服务器升级,导致原来的自动创建EXCHNAGE 2003邮箱的WebService代码无法正常运行了。让我帮忙给个方案如何进行EXCHANGE 2007的自动化代码开发。
这个东西其实主要是微软对于EXCHANGE 2007的API进行了大幅修改,取消了原来的CDEXCOM和MAPI的COM接口。代之以PowerShell作为第三方应用程序的编程接口。
了解之后代码方案比较简单了,通过调用PowerShell来进行邮箱的创建。花了大概1天的时间搭建了一个基于Hyper-V的EXCHANGE 2007的虚拟机做测试用(因为是笔记本,所以装软件花了很长时间,配置倒是简单的很),然后查阅了一下MSDN和SDK。写了段测试代码。
代码片段如下:
using System.ComponentModel;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Security;
using System.Configuration;
using System;
using Microsoft.PowerShell.Commands;
namespace ConsoleCreateMailBox
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("start to calling...");
AddPowerUser("Test3", "123456", "Test3@demo.local");
Console.WriteLine("function finished...");
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex);
Console.Read();
}
}
private static void AddPowerUser(string uname, string pword, string email)
{
//Create a runspace for your cmdlets to run and include the Exchange Management SnapIn...
RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
PSSnapInException PSException = null;
PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out PSException);
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
Command command = new Command("New-Mailbox");
command.Parameters.Add("Name", uname);
// now you must pass secure string
char[] passwordChars = pword.ToCharArray();
SecureString password = new SecureString();
foreach (char c in passwordChars)
{
password.AppendChar(c);
}
// these are the minimum parameters required
command.Parameters.Add("Password", password);
command.Parameters.Add("UserPrincipalName", email);
command.Parameters.Add("Database", ConfigurationManager.AppSettings["Database"].Trim()); //WIN2K3-EXH2007/Mailbox Database
command.Parameters.Add("OrganizationalUnit", ConfigurationManager.AppSettings["OrganizationalUnit"].Trim()); //Test
//set other mailbox parameters here
pipeline.Commands.Add(command);
Console.WriteLine("prepared the parameters...");
Console.WriteLine("start to calling PowerShell...");
Collection<PSObject> result = pipeline.Invoke();
Console.WriteLine("PowerShell Execution finished...");
}
}
}
在运行上述代码前,需要做些准备工作:
1、安装WINDOWS SDK,最好是6.1版本的。
2、引用PowerShell 的AUTOMATION DLL,路径: C:/Program Files/Reference Assemblies/Microsoft/WindowsPowerShell/v1.0/System.Management.Automation.dll
3、用VS2005及以上版本IDE,我的代码是在VS2008下编译开发的。
编译通过后,请在运行EXCHANGE 2007的服务器上跑一下这个程序,因为是需要实例化EXCHANGE FOR POWERSHELL的一个ADD-IN SNAPIN,所以在其他机器上跑是会报错的。
这段核心代码,可以修改下作为一个WCF服务在EXCHANGE SERVER上发布出来,供其他应用调用。
码海无涯,愿与诸君共勉之!