4
votes

I am writing a c# Windows Form app to migrate Exchange 2010 mailboxes to a file location on the server in .pst format. I used an example from the Powershell SDK (Runspace05) to access the exchange cmdlets (Get-Mailbox) and populate a combo-box with the users mailboxes with no problem.

The parts i'm having trouble with is getting the New-MailboxExportRequest cmdlet (the cmdlet that performs the export) to run and the ability to return it's objects and show them in a listbox control. What am I missing? Thanks in advance for your help.

The Code:

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())
            {
                var mailbox = cmbEmailUserName.Text;
                var pstFile = txtFileSaveLocation.Text;
                const int badLimit = 100; //can be increased in necessary

                powershell.AddCommand("Microsoft.Exchange.Management.PowerShell.E2010\\New-MailboxExportRequest");
                powershell.AddParameter("Mailbox", mailbox);
                powershell.AddParameter("FilePath", pstFile);

                powershell.Runspace = myrunspace;                 
                Collection<PSObject> results = powershell.Invoke();

                foreach (PSObject thisResult in results)
                        {
                            lstBoxStatus.Items.Add(thisResult);
                        }
        myrunspace.Close();

            }
        }
1
What sort of information do you want in the ListBox? Do you want the raw oject and then you format the properies or do you want the output that PowerShell would generate? If it is the latter, AddCommand("Out-String") to the end of the pipeline to get a PowerShell formatted string as the result. - Keith Hill
When you run the command in the exchange management shell it returns a status... shows that the command has been queued up. I want to return that status in the window. - user2704769
If you just want to see the status as PowerShell displays it, then put a powershell.AddCommand("Out-String") after the last AddParameter above. The result you get will be a string but that string should contain the status as PowerShell would have displayed it. - Keith Hill

1 Answers

1
votes

You want to access the properties of the PSObject, not the object itself.

Try this:

foreach (PSObject thisResult in results)
{
    foreach (PSPropertyInfo thisResultInfo in thisResult.Properties)
    {
        lstBoxStatus.Items.Add("Name: {0} Value: {1} Type: {2}", thisResultInfo.Name, thisResultInfo.Value, thisResultInfo.MemberType);
    }
}