-->

Create mailbox on exchange 2010 using C#

2019-06-05 17:41发布

问题:

I am trying to create a user mailbox on Exchange 2010 through my C# windows app. Here is my code

        PSCredential creds = new PSCredential("user id", StringToSecureString("password"));
        System.Uri uri = new Uri("http://servername/powershell?serializationLevel=Full");

        Runspace runspace = RunspaceFactory.CreateRunspace();

        PowerShell powershell = PowerShell.Create();
        PSCommand command = new PSCommand();
        command.AddCommand("New-PSSession");
        command.AddParameter("ConfigurationName", "Microsoft.Exchange");
        command.AddParameter("ConnectionUri", uri);
        command.AddParameter("Credential", creds);
        command.AddParameter("Authentication", "Default");
        powershell.Commands = command;
        runspace.Open();
        powershell.Runspace = runspace;
        Collection<PSSession> result = powershell.Invoke<PSSession>();

        powershell = PowerShell.Create();
        command = new PSCommand();
        command.AddCommand("Set-Variable");
        command.AddParameter("Name", "ra");
        command.AddParameter("Value", result[0]);
        powershell.Commands = command;
        powershell.Runspace = runspace;
        powershell.Invoke();

        powershell = PowerShell.Create();
        command = new PSCommand();
        command.AddScript("Import-PSSession -Session $ra");
        powershell.Commands = command;
        powershell.Runspace = runspace;
        powershell.Invoke();

        powershell = PowerShell.Create();
        command.AddCommand("Invoke-Command");
        command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("New-Mailbox"));
        command.AddParameter("Name", "FnameLname");
        command.AddParameter("Password", "abcd@123");
        command.AddParameter("Alias", "FLname");
        command.AddParameter("OrganizationalUnit", "Company/OU");
        command.AddParameter("UserPrincipalName", "Fname.Lname@Domain.com");
        command.AddParameter("SamAccountName", "FLname");
        command.AddParameter("FirstName", "Fname");
        command.AddParameter("Initials", "FL");
        command.AddParameter("LastName", "Lname");
        command.AddParameter("Database", "dbname");
        command.AddParameter("LinkedMasterAccount", @"company\FLname");
        command.AddParameter("LinkedDomainController", "domain controller");
        powershell.Commands = command;
        powershell.Runspace = runspace;
        var createmailbox = powershell.Invoke();

But I get the below error when I execute the above code.

A parameter cannot be found that matches parameter name 'Name'