Powershell脚本设计将消息体写入日志

时间:2016-06-15 15:20:21

标签: email powershell foreach

我正在尝试解析我的Outlook收件箱并匹配某些邮件,然后,对于每个匹配项,将电子邮件邮件正文写入我的应用程序日志。到目前为止我的代码在下面,但我发现脚本为每个匹配写了相同的消息。意思是,脚本存储的最后一个消息体,为过滤器捕获的每个匹配写入X次。

 Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null 
 $olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]  
 $outlook = new-object -comobject outlook.application 
 $namespace = $outlook.GetNameSpace("MAPI") 
 $inbox = $namespace.getDefaultFolder($olFolders::olFolderInBox) 
 $filter = (%{$inbox.items | Where {$_.SenderName -match ‘TestUser’ -and $_.UnRead -eq $true}})
 $filter.count

 foreach ($msg in $filter)
 {
 $MsgBody = $filter | select-object Body | format-table -HideTableHeaders -Wrap | Out-String
}

for ($i = $filter.count; $i -gt 0 ; $i --) {
Write-eventlog -logname Application -source "TestAlerts" -eventID 100 -entrytype Information -message "$MsgBody"
#$($msg)[$i].UnRead -eq $false - this still isn't working either.

}

1 个答案:

答案 0 :(得分:0)

试试这个:

for ($i = $filter.count; $i -gt 0 ; $i --) {
 $msg = $filter[$i]
 $MsgBody = $msg | select-object Body | format-table -HideTableHeaders -Wrap | Out-String
 Write-eventlog -logname Application -source "TestAlerts" -eventID 100 -entrytype Information -message "$MsgBody"
}