简体   繁体   English

交换Powershell C#

[英]Exchange Powershell C#

Ok so I have no hair left to tear out, so before my fingernails become non existent I thought I better post on here to see if anyone can shed some light. 好的,所以我没有剩下的头发可以撕掉,所以在我的指甲不存在之前,我想我最好在这里贴一下,看看是否有人可以照亮。

I have a C# application that randomly works, when I say randomly yesterday it was pulling out data perfectly, today it return absolutely nothing. 我有一个随机运行的C#应用​​程序,昨天我随机说它完美地提取了数据,今天却什么也没有返回。 My mission is to connect to the exchange management shell and perform a bunch of Get queries and return the results to a list. 我的任务是连接到交换管理外壳并执行一堆Get查询并将结果返回到列表。

Below is my exchange query code. 以下是我的交换查询代码。

public class EmsSession
    {
        public static List<Lists.ExchangeOverview> ExchOverview()
        {
            List<Lists.ExchangeOverview> data = new List<Lists.ExchangeOverview>();
            PowerShell powershell = PowerShell.Create();
            PSSnapInException ex;
            powershell.Runspace.RunspaceConfiguration.AddPSSnapIn(Program.SnapInString, out ex);
            if (ex != null) throw ex;
            powershell.AddScript(". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1");
            powershell.AddScript("Connect-ExchangeServer -auto");
            powershell.Invoke();
            powershell.Streams.ClearStreams();
            powershell.Commands.Clear();
            powershell.AddScript("Get-ExchangeServer | Select Name, Edition, AdminDisplayVersion, ServerRole");
            Collection<PSObject> results = powershell.Invoke();
            data.AddRange(results.Select(obj => new Lists.ExchangeOverview()
            {
                Name = obj.Members["Name"].Value.ToString(),
                Edition = obj.Members["Edition"].Value.ToString(),
                Version = obj.Members["AdminDisplayVersion"].Value.ToString(),
                Role = obj.Members["ServerRole"].Value.ToString()
            }));
            return data;
        }
        public static List<Lists.MailboxCount> MailboxDbCounts()
        {
            List<Lists.MailboxCount> data = new List<Lists.MailboxCount>();
            PowerShell powershell = PowerShell.Create();
            PSSnapInException ex;
            powershell.Runspace.RunspaceConfiguration.AddPSSnapIn(Program.SnapInString, out ex);
            if (ex != null) throw ex;
            powershell.AddScript(". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1");
            powershell.AddScript("Connect-ExchangeServer -auto");
            powershell.Invoke();
            powershell.Streams.ClearStreams();
            powershell.Commands.Clear();
            powershell.AddScript("Get-Mailbox | Group-Object -Property:Database | Select-Object name, count");
            Collection<PSObject> results = powershell.Invoke();
            data.AddRange(results.Select(obj => new Lists.MailboxCount()
            {
                Name = obj.Members["name"].Value.ToString(),
                Count = obj.Members["count"].Value.ToString()
            }));
            return data;
        }
        public static List<Lists.DatabaseInformation> DatabaseInformation()
        {
            List<Lists.DatabaseInformation> data = new List<Lists.DatabaseInformation>();
            PowerShell powershell = PowerShell.Create();
            PSSnapInException ex;
            powershell.Runspace.RunspaceConfiguration.AddPSSnapIn(Program.SnapInString, out ex);
            if (ex != null) throw ex;
            powershell.AddScript(". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1");
            powershell.AddScript("Connect-ExchangeServer -auto");
            powershell.Invoke();
            powershell.Streams.ClearStreams();
            powershell.Commands.Clear();
            powershell.AddScript("Get-MailboxDatabase -Status | Select Name, EdbFilePath, LogFolderPath");
            Collection<PSObject> results = powershell.Invoke();
            foreach (PSObject obj in results)
            {
                string edbSize = Functions.BytesToString(new System.IO.FileInfo(obj.Members["EdbFilePath"].Value.ToString()).Length, true);
                data.Add(new Lists.DatabaseInformation()
                {
                    Name = obj.Members["Name"].Value.ToString(),
                    DbSize = edbSize,
                    EdbPath = obj.Members["EdbFilePath"].Value.ToString(),
                    LogPath = obj.Members["LogFolderPath"].Value.ToString()
                });
            }
            return data;
        }
        public static ArrayList ExchangeTraffic()
        {
            ArrayList data = new ArrayList();
            StringBuilder stringBuild = new StringBuilder();
            stringBuild.AppendLine("$From = ((Get-Date).AddDays(-30)).Date");
            stringBuild.AppendLine("$To = ((Get-Date).AddDays(-29)).Date");
            stringBuild.AppendLine("[Int64] $intTotalSentInternally = $intTotalSentExternally = 0");
            stringBuild.AppendLine("[Int64] $intTotalRecInternally = $intTotalRecExternally = 0");
            stringBuild.AppendLine("[Int64] $intTotalSentSize = $intTotalSent = 0");
            stringBuild.AppendLine("[Int64] $intTotalRecSize = $intTotalRec = 0");
            stringBuild.AppendLine("[Int64] $intTotalFailed = 0");
            stringBuild.AppendLine("[Int64] $intTotalPoison = $intTotalPoisonHistory = 0");
            stringBuild.AppendLine("[String] $strEmails = $null ");
            stringBuild.AppendLine("Do");
            stringBuild.AppendLine("{");
            stringBuild.AppendLine(@"    $strEmails = ""$($From.ToString(""dd MMM"")),"" ");
            stringBuild.AppendLine("     $intTotalSentInternally = $intTotalSentExternally = 0");
            stringBuild.AppendLine("     $intTotalRecInternally = $intTotalRecExternally = 0");
            stringBuild.AppendLine("     $intTotalSentSize = $intTotalSent = 0");
            stringBuild.AppendLine("     $intTotalRecSize = $intTotalRec = 0");
            stringBuild.AppendLine("     $intTotalFailed = 0");
            stringBuild.AppendLine("     $intTotalPoison = 0");
            stringBuild.AppendLine("    (Get-TransportServer) | Get-MessageTrackingLog -ResultSize Unlimited -Start $From -End $To | ForEach {");
            stringBuild.AppendLine(@"         If ($_.EventId -eq ""RECEIVE"" -and $_.Source -eq ""STOREDRIVER"") {");
            stringBuild.AppendLine("            $intTotalSentSize += $_.TotalBytes");
            stringBuild.AppendLine("            $intTotalSent++");
            stringBuild.AppendLine(@"           If ($_.Recipients -match """ + Program.EmailDomain + @""") {");
            stringBuild.AppendLine("                $intTotalSentInternally++");
            stringBuild.AppendLine("            } Else {");
            stringBuild.AppendLine("                $intTotalSentExternally++");
            stringBuild.AppendLine("            }");
            stringBuild.AppendLine("        }");
            stringBuild.AppendLine(@"        If ($_.EventId -eq ""DELIVER"") {");
            stringBuild.AppendLine("            $intTotalRecSize += $_.TotalBytes");
            stringBuild.AppendLine("            $intTotalRec++");
            stringBuild.AppendLine(@"           If ($_.Sender -match """ + Program.EmailDomain + @""") {");
            stringBuild.AppendLine("                $intTotalRecInternally++");
            stringBuild.AppendLine("            } Else {");
            stringBuild.AppendLine("                $intTotalRecExternally++");
            stringBuild.AppendLine("            }");
            stringBuild.AppendLine("        }");
            stringBuild.AppendLine(@"        If ($_.EventId -eq ""FAIL"") {");
            stringBuild.AppendLine("            $intTotalFailed++");
            stringBuild.AppendLine("        }");
            stringBuild.AppendLine(@"        If ($_.EventId -eq ""POISONMESSAGE"") {");
            stringBuild.AppendLine("            $intTotalPoison++");
            stringBuild.AppendLine("        }");
            stringBuild.AppendLine("    }");
            stringBuild.AppendLine("    $intTotalPoison = $intTotalPoison - $intTotalPoisonHistory");
            stringBuild.AppendLine("    $intTotalPoisonHistory = $intTotalPoison");
            stringBuild.AppendLine(@"    $strEmails += ""$intTotalSent,$intTotalSentInternally,$intTotalSentExternally,$intTotalSentSize,$intTotalRec,$intTotalRecInternally,$intTotalRecExternally,$intTotalRecSize,$intTotalFailed,$intTotalPoison""");
            stringBuild.AppendLine("    $strEmails");
            stringBuild.AppendLine("    $From = $From.AddDays(1)");
            stringBuild.AppendLine("    $To = $From.AddDays(1)");
            stringBuild.AppendLine("}");
            stringBuild.AppendLine("While ($To -lt (Get-Date))");
            PowerShell powershell = PowerShell.Create();
            PSSnapInException ex;
            powershell.Runspace.RunspaceConfiguration.AddPSSnapIn(Program.SnapInString, out ex);
            if (ex != null) throw ex;
            powershell.AddScript(". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1");
            powershell.AddScript("Connect-ExchangeServer -auto");
            powershell.Invoke();
            powershell.Streams.ClearStreams();
            powershell.Commands.Clear();
            powershell.AddScript(stringBuild.ToString());
            Collection<PSObject> results = powershell.Invoke();
            foreach (PSObject obj in results)
            {
                data.Add(obj.ToString());
            }
            return data;
        }
        public static List<Lists.FailedEmails> FailedEmails()
        {
            List<Lists.FailedEmails> data = new List<Lists.FailedEmails>();
            StringBuilder strBuild = new StringBuilder();
            strBuild.AppendLine(@"[Array]$List_FailedEmailsBySender = Get-TransportServer | Get-MessageTrackingLog -ResultSize 'Unlimited' -EventID FAIL -Start ((Get-Date).AddDays(-30)).Date | Sort-Object -Property Sender | Group-Object -Property Sender");
            strBuild.AppendLine(@"$ProcessedList = New-Object -TypeName System.Collections.ArrayList");
            strBuild.AppendLine(@"foreach ($Sender in $List_FailedEmailsBySender) {");
            strBuild.AppendLine(@"    $Sender.Group | Select-Object -ExpandProperty Recipients | Sort-Object | Group-Object | ForEach-Object {");
            strBuild.AppendLine(@"        [VOID]$ProcessedList.Add((New-Object -TypeName psobject -Property @{");
            strBuild.AppendLine(@"            Sender = $Sender.Name");
            strBuild.AppendLine(@"            Recipient = $_.Name");
            strBuild.AppendLine(@"            FailedCount = $_.Count");
            strBuild.AppendLine(@"        }))");
            strBuild.AppendLine(@"    }");
            strBuild.AppendLine(@"}");
            strBuild.AppendLine(@"[Array]$Top20 = $ProcessedList | Sort-Object -Property FailedCount -Descending | Select-Object -First 20 | Select-Object -Property Sender,Recipient,FailedCount");
            strBuild.AppendLine(@"$Top20");
            PowerShell powershell = PowerShell.Create();
            PSSnapInException ex;
            powershell.Runspace.RunspaceConfiguration.AddPSSnapIn(Program.SnapInString, out ex);
            if (ex != null) throw ex;
            powershell.AddScript(". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1");
            powershell.AddScript("Connect-ExchangeServer -auto");
            powershell.Invoke();
            powershell.Streams.ClearStreams();
            powershell.Commands.Clear();
            powershell.AddScript(strBuild.ToString());
            Collection<PSObject> results = powershell.Invoke();
            data.AddRange(results.Select(obj => new Lists.FailedEmails()
            {
                Sender = obj.Members["Sender"].Value.ToString(),
                Recipient = obj.Members["Recipient"].Value.ToString(),
                Count = obj.Members["FailedCount"].Value.ToString()
            }));
            return data;
        }
        public static List<Lists.TopMailboxes> TopMailboxes()
        {
            List<Lists.TopMailboxes> data = new List<Lists.TopMailboxes>();
            PowerShell powershell = PowerShell.Create();
            PSSnapInException ex;
            powershell.Runspace.RunspaceConfiguration.AddPSSnapIn(Program.SnapInString, out ex);
            if (ex != null) throw ex;
            powershell.AddScript(". $env:ExchangeInstallPath\\bin\\RemoteExchange.ps1");
            powershell.AddScript("Connect-ExchangeServer -auto");
            powershell.Invoke();
            powershell.Streams.ClearStreams();
            powershell.Commands.Clear();
            powershell.AddScript("Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Sort-Object TotalItemSize -Descending | Select-Object DisplayName,@{name='TotalItemSize';expression={[math]::Round((($_.TotalItemSize.Value.ToString()).Split('(')[1].Split(' ')[0].Replace(',','')/1GB),2)}} -First 20");
            Collection<PSObject> results = powershell.Invoke();
            data.AddRange(results.Select(obj => new Lists.TopMailboxes()
            {
                MailboxName = obj.Members["DisplayName"].Value.ToString(),
                Size = obj.Members["TotalItemSize"].Value.ToString()
            }));
            return data;
        }
    }
}

I am not getting any errors from the server it is run on, I am just getting completely blank data. 我没有从运行它的服务器上收到任何错误,我只是获取完全空白的数据。

I can confirm that the variable Program.SnapInString returns the correct exchange snap in to use (which is Microsoft.Exchange.Management.Powershell.E2010) 我可以确认变量Program.SnapInString返回了要使用的正确的交换管理单元(这是Microsoft.Exchange.Management.Powershell.E2010)

Maybe tomorrow it will work again!! 也许明天它将再次工作!!

Any ideas would be amazing. 任何想法都将是惊人的。

---One more thing to add this runs as the system account (if that would make any difference, not as a logged on user) ---还有一件要添加的事情作为系统帐户运行(如果有什么不同,而不是以登录用户身份运行)

You can optimize it: 您可以对其进行优化:

public class EmsSession
    {
    static PSCredential cred = (PSCredential)null;
    static WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("http://exchangeserver01.my.domain/powershell?serializationLevel=Full"), 
                                                                         "http://schemas.microsoft.com/powershell/Microsoft.Exchange", cred);

    public static string GetPropertyValue(this PSObject psObject, string propertyName)
    {
        string ret = string.Empty;
        if (psObject.Properties[propertyName].Value != null)
            ret = psObject.Properties[propertyName].Value.ToString();

        return ret;
    }
    public static List<Lists.ExchangeOverview> ExchOverview()
    {
        var data = new List<Lists.ExchangeOverview>();          
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
        Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)
        PowerShell powershell = PowerShell.Create()

        Command cmd1 = new Command("Get-ExchangeServer");
        powershell.Commands.Commands.Add(cmd1);
        runspace.Open();
        powershell.Runspace = runspace;
        Collection<PSObject> psResults = powershell.Invoke();

        foreach (PSObject psResult in psResults)
        {
            data.AddRange(results.Select(obj => new Lists.ExchangeOverview()
                    {
                        Name = psResult.GetPropertyValue("Name"),
                        Edition = psResult.GetPropertyValue("ItemCount"),
                        Version = psResult.GetPropertyValue("AdminDisplayVersion"),
                        Role = psResult.GetPropertyValue("ServerRole"),
                    }));                
        }

        foreach (ErrorRecord psError in powershell.Streams.Error)
        {
            errors.Add(
                new emsErrorRecord
                {
                    Command = psError.CategoryInfo.Activity,
                    Reason = psError.CategoryInfo.Reason,
                    Message = psError.Exception.Message
                });
        }

        foreach (WarningRecord psWarning in powershell.Streams.Warning)
        {
            warnings.Add(
                new emsWarningRecord
                {
                    Command = psWarning.InvocationInfo.MyCommand.Name,
                    Message = psWarning.Message
                });
        }

        runspace.Dispose();
        runspace = null;

        powershell.Dispose();
        powershell = null;
        return data;
    }

    public static List<Lists.MailboxCount> MailboxDbCounts()
    {
        var data = new List<Lists.MailboxCount>();  
        var databases = DatabaseInformation();
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
        Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)
        PowerShell powershell = PowerShell.Create()

        Command cmd1 = new Command("Get-Mailbox");
        powershell.Commands.Commands.Add(cmd1);
        runspace.Open();
        powershell.Runspace = runspace;
        Collection<PSObject> psResults = powershell.Invoke();

        foreach (PSObject psResult in psResults)
        {
            foreach(Lists.DatabaseInformation database in databases)
            {
                int counter = 0;
                if(database.Name == psResult.GetPropertyValue("Name"))
                {
                    counter++;
                }
                data.Add(new Lists.MailboxCount()
                {
                    Name = obj.Members["name"].Value.ToString(),
                    Count = counter.ToString()
                }));
            }           
        }

        foreach (ErrorRecord psError in powershell.Streams.Error)
        {
            errors.Add(
                new emsErrorRecord
                {
                    Command = psError.CategoryInfo.Activity,
                    Reason = psError.CategoryInfo.Reason,
                    Message = psError.Exception.Message
                });
        }

        foreach (WarningRecord psWarning in powershell.Streams.Warning)
        {
            warnings.Add(
                new emsWarningRecord
                {
                    Command = psWarning.InvocationInfo.MyCommand.Name,
                    Message = psWarning.Message
                });
        }

        runspace.Dispose();
        runspace = null;

        powershell.Dispose();
        powershell = null;
    }           

    public static List<Lists.DatabaseInformation> DatabaseInformation()
    {
        var data = new List<Lists.DatabaseInformation>();       
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
        Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)
        PowerShell powershell = PowerShell.Create()

        Command cmd1 = new Command("Get-MailboxDatabase");
        powershell.Commands.Commands.Add(cmd1);
        runspace.Open();
        powershell.Runspace = runspace;
        Collection<PSObject> psResults = powershell.Invoke();

        foreach (PSObject psResult in psResults)
        {
            string edbSize = Functions.BytesToString(new System.IO.FileInfo(obj.Members["EdbFilePath"].Value.ToString()).Length, true);
            data.AddRange(results.Select(obj => new Lists.MailboxCount()
                    {
                        Name = psResult.GetPropertyValue("Name"),
                        DbSize = edbSize,
                        EdbPath = psResult.GetPropertyValue("EdbFilePath"),
                        LogPath = psResult.GetPropertyValue("LogFolderPath")
                    }));                
        }

        foreach (ErrorRecord psError in powershell.Streams.Error)
        {
            errors.Add(
                new emsErrorRecord
                {
                    Command = psError.CategoryInfo.Activity,
                    Reason = psError.CategoryInfo.Reason,
                    Message = psError.Exception.Message
                });
        }

        foreach (WarningRecord psWarning in powershell.Streams.Warning)
        {
            warnings.Add(
                new emsWarningRecord
                {
                    Command = psWarning.InvocationInfo.MyCommand.Name,
                    Message = psWarning.Message
                });
        }

        runspace.Dispose();
        runspace = null;

        powershell.Dispose();
        powershell = null;
    }
}       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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