简体   繁体   中英

Powershell Command Will not run in C#

I am writing ac# 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();

            }
        }

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM