使用 C# Powershell 获取到 Exchange 服务器的 MessageTrace

Get-MessageTrace to Exchange Server Using C# Powershell

目前我有一个 Powershell 脚本,它创建一个会话,然后使用以下查询查询 Exchange 电子邮件:

Get-MessageTrace -StartDate "10/07/2017 12:00 AM" -EndDate "11/06/2017 11:59 PM" -PageSize 5000 -Page $Page | Select Received,SenderAddress,RecipientAddress,Size

我想更新此脚本,使其 运行 在 C# 中运行,这样我就可以 运行 将其作为一项服务,开始日期和结束日期等字段会自动更新。为此,我已经到了可以与服务器创建会话然后 运行 以下方法的地步:

private static List<PSObject> RetrieveCurrentEmailList(string previousDate, DateTime currentDate, int pageSize,
        int currentPage, IReadOnlyList<PSObject> psConnection, Runspace runspace)
    {
        var powershell = PowerShell.Create();
        var command = new PSCommand();
        command.AddCommand("Invoke-Command");
        command.AddParameter("ScriptBlock",
            ScriptBlock.Create(
                "Get-MessageTrace -StartDate \"" + previousDate
                + "\" -EndDate \"" + currentDate.ToString("MM/dd/yyyy", CultureInfo.CreateSpecificCulture("en-US"))
                + "\" -pageSize " + pageSize
                + " -Page " + currentPage));
        //+ " | Select Received,SenderAddress,RecipientAddress,Size"));
        command.AddParameter("Session", psConnection[0]);
        powershell.Commands = command;
        powershell.Runspace = runspace;
        Console.WriteLine("Executing query for page: " + currentPage);
        return powershell.Invoke().ToList();
    }

其中returns整个PSObject。但是,当我尝试包含“| Select Received,SenderAddress,RecipientAddress,Size”过滤时,它会停止返回结果。最重要的是,我必须处理 运行 空间并在每次我想要 运行 这种方法(或任何查询,它似乎是 1 运行空格,1 个查询)。它通常会返回大约 30,000 个结果,而我一次可以得到的最大大小是 5,000,这使得这个过程非常耗时。

我是这种 Powershell/C# 集成的新手,所以我不确定我缺少什么。如果你们中有人知道我在处理此类操作时如何包含过滤或有任何 advice/best 实践,我将不胜感激。

假设您的运行空间已通过 New-PSSession 和 Import-PSSession 连接到 Exchange,则您不需要使用 Invoke-Command。请参阅 post 了解如何做到这一点:Exchange PowerShell commands through C#

添加“| Select...”失败的原因是它需要在 ScriptBlock.Create() 字符串中。无论如何,下面是(恕我直言)一种更简洁的方法:

using (var powershell = PowerShell.Create())
{
    powershell.Runspace = runspace;
    powershell
       .AddCommand("Get-MessageTrace")
       .AddParameter("StartDate", previousDate)
       .AddParameter("EndDate", currentDate)
       .AddParameter("PageSize", pageSize)
       .AddParameter("Page", currentPage)
       .AddCommand("Select-Object")
       .AddParameter("Property", new string[] { "Received", "SenderAddress", "RecipientAddress", "Size" });

    Console.WriteLine("Executing query for page: " + currentPage);
    return powershell.Invoke().ToList();
}

您应该能够重新使用您的运行空间,而无需每次都重新创建它。但是,另一种方法是使用 PowerShell 对象而不是运行空间。有关详细信息,请参阅上面的 link。