0

When trying to create a new mailbox with C# and the Exchange Shell I do not get any errors, but the data is not being pushed to the server. If I do make an error like putting a string in the password field I get an error message. I can also do this process manually and it works. Should I be supplying more information or is this implementation outdated. Here is the code that I am currently using:

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

            Boolean success = false;
            RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
            SecureString spassword = new SecureString();
            spassword.Clear();

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

            PSSnapInException snapInException = null;
            PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
            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", false);
            myCommand.Parameters.Add("SamAccountName", Alias);
            myCommand.Parameters.Add("FirstName", FirstName);
            myCommand.Parameters.Add("LastName", LastName);
            myCommand.Parameters.Add("Password", "pass");
            myCommand.Parameters.Add("ResetPasswordOnNextLogon", false);
            myCommand.Parameters.Add("OrganizationalUnit", OrganizationalUnit);
            pipeLine.Commands.Add(myCommand);
            pipeLine.Commands.Add(myCommand);

            try
            {
                pipeLine.Invoke();
                Console.WriteLine("ERROR:", pipeLine.Error.ToString());


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
            finally
            {
                myRunSpace.Dispose();
                success = true;
            }
            return success;
        } 
jfrost
  • 1
  • Why do you have `pipeLine.Commands.Add(myCommand);` twice? – Daniel Oct 01 '21 at 20:07
  • Not sure why but the example I used had it. I tried both once and twice an both, both did not work so I left it like the example – jfrost Oct 01 '21 at 20:28
  • Why are you creating a secure password `spassword`, but do not use it? (`myCommand.Parameters.Add("Password", "pass");`) ? – Theo Oct 02 '21 at 10:21

0 Answers0