using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.DirectoryServices;
using Microsoft.PowerShell.Commands;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Security;
using System.Configuration;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Management;
using System.Management.Instrumentation;
using System.Security.Principal;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Text;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Runtime.InteropServices;
namespace Testmail
{
/// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
private static IntPtr _userToken = IntPtr.Zero;
private static WindowsImpersonationContext _impersonationContext = null;
[WebMethod]
public void AddPowerUser(string uname, string pword, string email)
{
//Create a runspace for your cmdlets to run and include the Exchange Management SnapIn...
try
{
RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
PSSnapInException PSException = null;
PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
//登陆邮箱服务器
BeginImpersonation(ConfigurationManager.AppSettings["Domain"].Trim());
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf))
{
try
{
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("LastName", uname);
//Command.Parameters.Add("Initials", "");
//Command.Parameters.Add("FirstName", uname);
//Command.Parameters.Add("DisplayName", uname + "*" + "flag");
Command.Parameters.Add("-UserPrincipalName", email);
//Command.Parameters.Add("SamAccountName", uname);
Command.Parameters.Add("-Alias", uname);
Command.Parameters.Add("-Name", uname);
Command.Parameters.Add("-Password", password);
Command.Parameters.Add("-Database", ConfigurationManager.AppSettings["Database"].Trim());
Command.Parameters.Add("-OrganizationalUnit", ConfigurationManager.AppSettings["OrganizationalUnit"].Trim());
Command.Parameters.Add("-ResetPasswordOnNextLogon", true);
//Command.Parameters.Add("-DomainController", ConfigurationManager.AppSettings["DomainController"].Trim());
//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...");
try
{
Collection<PSObject> result = pipeline.Invoke();
}
catch (Exception exx)
{
throw new Exception(exx.Message);
}
// Check for errors in the pipeline and throw an exception if necessary.
//if (pipeline.Error != null && pipeline.Error.Count > 0)
//{
// StringBuilder pipelineError = new StringBuilder();
// pipelineError.AppendFormat("Error calling New-Mailbox.");
// foreach (object item in pipeline.Error.ReadToEnd())
// {
// pipelineError.AppendFormat("{0}\n", item.ToString());
// }
// throw new Exception(pipelineError.ToString());
//}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
runspace.Close();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
public static void BeginImpersonation(string domain)
{
//Please change the User Name and Password
string UserName = System.Configuration.ConfigurationManager.AppSettings["ExchangeAdminUser"];
string Password = System.Configuration.ConfigurationManager.AppSettings["ExchangeAdminPwd"];
EndImpersonation();
bool success = LogonUser(
UserName,
domain,
Password,
2,
0,
ref _userToken);
// Did it work?
if (!success) throw new Exception(string.Format("LogonUser returned error {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
WindowsIdentity fakeId = new WindowsIdentity(_userToken);
_impersonationContext = fakeId.Impersonate();
}
public static void EndImpersonation()
{
if (_impersonationContext != null)
{
try
{
_impersonationContext.Undo();
}
finally
{
_impersonationContext.Dispose();
_impersonationContext = null;
}
}
}
}
}