在Exchange上查找邮件

时间:2018-01-26 13:01:44

标签: c# powershell exchange-server

我想让一个程序在Exchange服务器上查找邮件使用GUI界面。 我们可以使用poweshell命令行开关来查找邮件:

Get-MessageTrackingLog -Server myserver -Start '01/25/2018 00:00:00' -End '01/25/2018 01:00:00' -Recipients 'user@domain'

这是我的程序C#:

string connectionUri = "http://myserver/PowerShell/";
string loginPassword = textBox2.Text; // password
SecureString secpassword = new SecureString();
foreach (char c in loginPassword)
{
secpassword.AppendChar(c);
}
PSCredential credential = new PSCredential(textBox1.Text, secpassword); // login and password
unspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand(); 
command.AddCommand("New-PSSession")
.AddParameter("ConfigurationName", "Microsoft.Exchange")
.AddParameter("ConnectionUri", new Uri(connectionUri))
.AddParameter("Authentication", "Kerberos")
.AddParameter("Credential", credential);
powershell.Commands = command;
runspace.Open();
powershell.Runspace = runspace;
Collection<System.Management.Automation.PSObject> result = powershell.Invoke();
powershell = PowerShell.Create();
command = new PSCommand();
command.AddCommand("Invoke-Command");
command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Get-MessageTrackingLog -Start '01/25/2018 00:00:00' -End '01/25/2018 01:00:00' -Recipients 'user@domain'"));
// command.AddParameter("ScriptBlock", System.Management.Automation.ScriptBlock.Create("Get-Mailbox"));
command.AddParameter("Session", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
var mailBoxes = powershell.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder(); // Convert result StringBuilder;
foreach (PSObject obj in mailBoxes)
{
stringBuilder.AppendLine(obj.ToString());
}
textBox3.Text = stringBuilder.ToString();

程序连接到我的服务器并查找邮件(3条消息),但输出结果不正确:

Microsoft.Exchange.Management.TransportLogSearchTasks.MessageTrackingEvent
Microsoft.Exchange.Management.TransportLogSearchTasks.MessageTrackingEvent
Microsoft.Exchange.Management.TransportLogSearchTasks.MessageTrackingEvent

如何使输出正确?

3 个答案:

答案 0 :(得分:0)

在.net中,任何对象上的ToString()的默认实现只返回对象类型的完全限定名称。要打印对象的内容,必须显式打印对象的每个成员。

foreach (PSObject obj in mailBoxes)
{
   stringBuilder.AppendLine(obj.MessageInfo);
   stringBuilder.AppendLine(obj.MessageId);

   .....
}

希望你明白这一点。

答案 1 :(得分:0)

我尝试从Exchange服务器连接 Microsoft.Exchange.Management.dll 并添加下一个代码:

using Microsoft.Exchange.Management.TransportLogSearchTasks;
.....
foreach (PSObject obj in mailBoxes){
  MessageTrackingEvent mte = (MessageTrackingEvent) obj;
  stringBuilder.AppendLine(mte.MessageInfo);
}

错误,CS0030无法转换类型&#39; System.Management.Automation.PSObject&#39;

答案 2 :(得分:0)

我解决了问题

foreach (PSObject obj in mailBoxes)
{
stringBuilder.AppendLine(obj.Properties["Sender"].Value.ToString());
}