【问题标题】:Powershell Command Will not run in C#Powershell 命令不会在 C# 中运行
【发布时间】:2013-08-27 17:51:54
【问题描述】:

我正在编写一个 c# Windows 窗体应用程序,以将 Exchange 2010 邮箱迁移到服务器上 .pst 格式的文件位置。我使用了 Powershell SDK (Runspace05) 中的一个示例来访问交换 cmdlet (Get-Mailbox),并毫无问题地使用用户邮箱填充组合框。

我遇到问题的部分是让 New-MailboxExportRequest cmdlet(执行导出的 cmdlet)运行,并能够返回它的对象并在列表框控件中显示它们。我错过了什么?提前感谢您的帮助。

代码:

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

            }
        }

【问题讨论】:

  • 你想在 ListBox 中提供什么样的信息?您想要原始对象然后格式化属性还是想要 PowerShell 生成的输出?如果是后者,则 AddCommand("Out-String") 到管道的末尾得到一个 PowerShell 格式的字符串作为结果。
  • 当您在 Exchange Management Shell 中运行该命令时,它会返回一个状态...表明该命令已排队。我想在窗口中返回那个状态。
  • 如果您只想查看 PowerShell 显示的状态,请在上面的最后一个 AddParameter 之后放置 powershell.AddCommand("Out-String")。您得到的结果将是一个字符串,但该字符串应该包含 PowerShell 显示的状态。

标签: c# powershell exchange-server-2010


【解决方案1】:

您想访问PSObject 的属性,而不是对象本身。

试试这个:

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

【讨论】:

  • VS 不喜欢您的代码编写方式,因此我不得不对其进行修改以使其能够编译。然而,它并没有产生预期的结果。这是我对您的代码的编辑: foreach (PSObject thisResult in results) { foreach (PSPropertyInfo thisResultInfo in thisResult.Properties) { lstBoxStatus.Items.Add(string.Format("Name: {0} Value: {1} Type: { 2}", thisResultInfo.Name, thisResultInfo.Value, thisResultInfo.MemberType)); } }
  • 您的修改输出有什么问题?您可能需要使用类似 thisResult.Members[thisResultInfo.Name].Value 的方式访问该值
  • 修改没有产生任何输出......这让我摸不着头脑。
  • 检查 powershell.HadErrors。也许没有结果,因为您正在执行的命令中有错误。您确定该命令不应该只是 New-MailboxExportRequest 而不是它前面的管理单元名称吗?还是它产生了一些 PSObject,只是没有属性?
猜你喜欢
  • 2011-03-02
  • 1970-01-01
  • 2016-05-18
  • 2021-01-08
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多