C# 在c中创建exchange邮箱#

C# 在c中创建exchange邮箱#,c#,powershell,exchange-server-2013,C#,Powershell,Exchange Server 2013,我想在exchange server 2013中使用c#创建邮箱 我尝试了很多代码,但每个代码都有一个错误,即没有明显的解决方案 我的代码是 public static Boolean CreateUser(string FirstName, string LastName, string Alias,string PassWord, string DomainName, string OrganizationalUnit) { string Name = FirstNa

我想在exchange server 2013中使用c#创建邮箱

我尝试了很多代码,但每个代码都有一个错误,即没有明显的解决方案

我的代码是

public static Boolean CreateUser(string FirstName, string LastName, string Alias,string PassWord, string DomainName, string OrganizationalUnit)
    {
        string Name = FirstName + " " + LastName;
        string PrincipalName = FirstName + "." + LastName + "@" + DomainName;

        Boolean success = false;
        string consolePath = @"C:\Program Files\Microsoft\Exchange Server\V15\bin\exshell.psc1";
        PSConsoleLoadException pSConsoleLoadException = null;
        RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(consolePath, out pSConsoleLoadException);
        SecureString spassword = new SecureString();
        spassword.Clear();

        foreach (char c in PassWord)
        {
            spassword.AppendChar(c);
        }

        PSSnapInException snapInException = null;
        Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
        myRunSpace.Open();
        Pipeline pipeLine = myRunSpace.CreatePipeline();

        Command myCommand = new Command("New-MailBox");
        myCommand.Parameters.Add("Name", Name);
        myCommand.Parameters.Add("Alias", Alias);
        myCommand.Parameters.Add("UserPrincipalName", PrincipalName);
        myCommand.Parameters.Add("Confirm", true);
        myCommand.Parameters.Add("SamAccountName", Alias);
        myCommand.Parameters.Add("FirstName", FirstName);
        myCommand.Parameters.Add("LastName", LastName);
        myCommand.Parameters.Add("Password", spassword);
        myCommand.Parameters.Add("ResetPasswordOnNextLogon", false);
        myCommand.Parameters.Add("OrganizationalUnit", OrganizationalUnit);
        pipeLine.Commands.Add(myCommand);
        pipeLine.Invoke();     // got an error here
        myRunSpace.Dispose();
       }
并称之为:

Boolean Success = CreateUser("firstname", "lastName", "aliasName", "AAaa12345", "mydomain.com", "mydomain.com/Users");
我得到这个错误:

Additional information: The term 'New-MailBox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
我测试的另一个代码是:

string userName = "administrator";
        string password = "mypass";
        System.Security.SecureString securePassword = new System.Security.SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        PSCredential credential = new PSCredential(userName, securePassword);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://{my server IP}/POWERSHELL/Microsoft.Exchange"),
        "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
        credential);

        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
        connectionInfo.SkipCACheck = true;
        connectionInfo.SkipCNCheck = true;
        connectionInfo.MaximumConnectionRedirectionCount = 2;

        using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            runspace.Open();
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = runspace;
                //Create the command and add a parameter
                powershell.AddCommand("Get-Mailbox");
                powershell.AddParameter("RecipientTypeDetails", "UserMailbox");
                //Invoke the command and store the results in a PSObject collection
                Collection<PSObject> results = powershell.Invoke();
                //Iterate through the results and write the DisplayName and PrimarySMTP
                //address for each mailbox
                foreach (PSObject result in results)
                {
                    Console.WriteLine(
                        string.Format("Name: { 0}, PrimarySmtpAddress: { 1}",

                result.Properties["DisplayName"].Value.ToString(),
                result.Properties["PrimarySmtpAddress"].Value.ToString()

                ));

                }
            }
        }
我想我已经给了我的管理员用户所需的所有权限,防火墙已经关闭,但它还不能工作

任何帮助或提示!! 谢谢

试试这个:

//Secure String

string pwd = "Password";
char[] cpwd = pwd.ToCharArray();
SecureString ss = new SecureString();
foreach (char c in cpwd)
ss.AppendChar(c);

//URI

Uri connectTo = new Uri("http://exchserver.domain.local/PowerShell");
string schemaURI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";

//PS Credentials

PSCredential credential = new PSCredential("Domain\\administrator", ss);

WSManConnectionInfo connectionInfo = new WSManConnectionInfo(connectTo, schemaURI, credential);
connectionInfo.MaximumConnectionRedirectionCount = 5;
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
remoteRunspace.Open();

PowerShell ps = PowerShell.Create();
ps.Runspace = remoteRunspace;

ps.Commands.AddCommand("Get-Mailbox");
ps.Commands.AddParameter("Identity","user@domain.local");

foreach (PSObject result in ps.Invoke()) 
{
Console.WriteLine("{0,-25}{1}", result.Members["DisplayName"].Value,
result.Members["PrimarySMTPAddress"].Value);
}
我取消选中“首选32位”,并将平台目标更改为x64,问题就解决了

使用以下代码:

 public class ExchangeShellExecuter
{

    public Collection<PSObject> ExecuteCommand(Command command)
    {
        RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
        PSSnapInException PSException = null;
        PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.Add(command);
        Collection<PSObject> result = pipeline.Invoke();
        return result ;
    }
}
    public class ExchangeShellCommand
{
    public Command NewMailBox(string userLogonName,string firstName,string lastName,string password
        ,string displayName,string organizationUnit = "mydomain.com/Users", 
        string database = "Mailbox Database 1338667540", bool resetPasswordOnNextLogon = false)
    {
        try
        {
            SecureString securePwd = ExchangeShellHelper.StringToSecureString(password);
            Command command = new Command("New-Mailbox");
            var name = firstName + " " + lastName;

            command.Parameters.Add("FirstName", firstName);
            command.Parameters.Add("LastName", lastName);
            command.Parameters.Add("Name", name);

            command.Parameters.Add("Alias", userLogonName);
            command.Parameters.Add("database", database);
            command.Parameters.Add("Password", securePwd);
            command.Parameters.Add("DisplayName", displayName);
            command.Parameters.Add("UserPrincipalName", userLogonName+ "@mydomain.com");
            command.Parameters.Add("OrganizationalUnit", organizationUnit);
            //command.Parameters.Add("ResetPasswordOnNextLogon", resetPasswordOnNextLogon);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
    }

    public Command AddEmail(string email, string newEmail)
    {
        try
        {
            Command command = new Command("Set-mailbox");
            command.Parameters.Add("Identity", email);
            command.Parameters.Add("EmailAddresses", newEmail);
            command.Parameters.Add("EmailAddressPolicyEnabled", false);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
        //
    }

    public Command SetDefaultEmail(string userEmail, string emailToSetAsDefault)
    {
        try
        {
            Command command = new Command("Set-mailbox");
            command.Parameters.Add("Identity", userEmail);
            command.Parameters.Add("PrimarySmtpAddress", emailToSetAsDefault);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
        //PrimarySmtpAddress
    }


}

.... 未为目标配置。如果不需要Kerberos,请指定协商身份验证机制并重新提交操作。有关详细信息,请参阅关于远程疑难解答帮助主题。exchange服务器是在广告内部还是外部?如果在外部,请使用基本身份验证。我会收到以下错误:其他信息:连接到远程服务器mydomain.com失败,错误消息如下:WinRM无法处理该请求。使用Kerberos身份验证时发生以下错误:Kerberos未知计算机mydomain.com。验证网络上是否存在该计算机,提供的名称拼写是否正确,以及访问该计算机的Kerberos配置是否正确。最常见的Kerberos配置问题是格式为HTTP/mydomain.com的SPN
 public class ExchangeShellExecuter
{

    public Collection<PSObject> ExecuteCommand(Command command)
    {
        RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
        PSSnapInException PSException = null;
        PSSnapInInfo info = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.Add(command);
        Collection<PSObject> result = pipeline.Invoke();
        return result ;
    }
}
    public class ExchangeShellCommand
{
    public Command NewMailBox(string userLogonName,string firstName,string lastName,string password
        ,string displayName,string organizationUnit = "mydomain.com/Users", 
        string database = "Mailbox Database 1338667540", bool resetPasswordOnNextLogon = false)
    {
        try
        {
            SecureString securePwd = ExchangeShellHelper.StringToSecureString(password);
            Command command = new Command("New-Mailbox");
            var name = firstName + " " + lastName;

            command.Parameters.Add("FirstName", firstName);
            command.Parameters.Add("LastName", lastName);
            command.Parameters.Add("Name", name);

            command.Parameters.Add("Alias", userLogonName);
            command.Parameters.Add("database", database);
            command.Parameters.Add("Password", securePwd);
            command.Parameters.Add("DisplayName", displayName);
            command.Parameters.Add("UserPrincipalName", userLogonName+ "@mydomain.com");
            command.Parameters.Add("OrganizationalUnit", organizationUnit);
            //command.Parameters.Add("ResetPasswordOnNextLogon", resetPasswordOnNextLogon);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
    }

    public Command AddEmail(string email, string newEmail)
    {
        try
        {
            Command command = new Command("Set-mailbox");
            command.Parameters.Add("Identity", email);
            command.Parameters.Add("EmailAddresses", newEmail);
            command.Parameters.Add("EmailAddressPolicyEnabled", false);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
        //
    }

    public Command SetDefaultEmail(string userEmail, string emailToSetAsDefault)
    {
        try
        {
            Command command = new Command("Set-mailbox");
            command.Parameters.Add("Identity", userEmail);
            command.Parameters.Add("PrimarySmtpAddress", emailToSetAsDefault);

            return command;
        }
        catch (Exception)
        {

            throw;
        }
        //PrimarySmtpAddress
    }


}
 var addEmailCommand = new ExchangeShellCommand().AddEmail("unos4@mydomain.com","unos.bm65@yahoo.com");
        var res2 = new ExchangeShellExecuter().ExecuteCommand(addEmailCommand);

        var emailDefaultCommand = new ExchangeShellCommand().AddSetDefaultEmail("unos4@mydomain.com", "unos.bm65@yahoo.com");
        var res3 = new ExchangeShellExecuter().ExecuteCommand(emailDefaultCommand);