2015-10-22 96 views
1

好吧,我沒有頭髮留下來撕掉,所以在我的指甲變得不存在之前,我想我最好在這裏發帖,看看是否有人可以擺脫一些光。Exchange Powershell C#

我有一個隨機工作的C#應用​​程序,當我昨天說隨機抽取數據時,它今天完全沒有返回。我的任務是連接到Exchange管理shell並執行一堆Get查詢並將結果返回到列表。

以下是我的交換查詢碼。

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

我沒有從它運行的服務器收到任何錯誤,我只是得到完全空白的數據。

我可以證實,該變量Program.SnapInString返回正確的交換單元中使用(這是Microsoft.Exchange.Management.Powershell.E2010)

也許明天它會再次工作!

任何想法都會很棒。

---一件事添加此運行的系統帳戶(如果這將使任何區別,不作爲登錄的用戶)

+0

爲什麼不只使用powershell腳本,不使用c#包裝,或者如果您使用的是C#,然後使用Exchange API,它是非常好的文檔(https://msdn.microsoft.com/en-us/library/office/dn567668(v = exchg 0.150)的.aspx)。 – vittore

+0

我不僅僅使用powershell腳本的原因是,一旦捕獲了這些數據,C#程序將根據這些數據生成PDF報告,並將該數據導入到SQL數據庫中 –

+0

如果我可以使其可靠地工作,並且如果任何人都有興趣我很高興發佈完整的代碼,因爲報告非常酷(在我的愚見) –

回答

0

則可對其進行優化:

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; 
    } 
}  
相關問題