1

I am writing a WinForms application in C# that will ultimately migrate Exchange 2010 mailboxes to a file location (pstStore) in .pst format. The form consists of a collection of textboxes, combo boxes and radio buttons. The command that will do the work is New-MailboxExportRequest –Mailbox… -FilePath… after a button click.

I am accessing the Exchange Management shell and using a runspace to pass the cmdlet and parameters. In the Parameters (-Mailbox and –FilePath) I want to pass the values of the textboxes and combo boxes. How do I do this in C#?

FYI… I’m using the same code to populate a combo box with all of the mailboxes from the exchange database. So the code works for that purpose so, I thought I could also use it to pass some variables into with the AddParameter method.

Here is the code from the click event:

 InitialSessionState iss = InitialSessionState.CreateDefault();
    PSSnapInException warning;          iss.ImportPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010",out warning);
    using (Runspace myrunspace = RunspaceFactory.CreateRunspace(iss))
    {
       myrunspace.Open();                                
       using (PowerShell powershell = PowerShell.Create())                    
        {              powershell.AddCommand("Microsoft.Exchange.Management.PowerShell.E2010\\New-MailboxExportRequest")
    powershell.AddParameter("Mailbox", "UserMailbox");
    powershell.AddParameter("FilePath", "ExchAdmin");
    powershell.AddParameter("","");
    powershell.Runspace = myrunspace;
    Collection<PSObject> results = null;
    try
    {
       results = powershell.Invoke(); //Runs the cmdlet synchronously  
    }
    catch (RuntimeException ex)
     {
        foreach (PSObject thisResult in results)
        {
           lstBoxStatus.Items.Add(thisResult); //sending the result to a status window
        }
     }                
     myrunspace.Close();
    }

1 Answer 1

1

When you call the AddParameter overload that takes two parameters, the second one is the value. Just use the name of the C# variable there e.g.:

string mailbox = _mailBoxTextBox.Text;
...
powershell.AddParameter("Mailbox", mailbox);
Sign up to request clarification or add additional context in comments.

1 Comment

Right now that seems to do the trick. I had the variables in the wrong scope. Once I fixed that the parameters were excepted. Still more work to be done so it's not too clunky but, thanks for the clarity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.