使用EWS检查未读交换邮件的数量
问题描述:
我是使用PowerShell的新手,目前正在使用脚本来检查共享邮箱是否包含未读邮件。 我目前正在试图用FindItems()
方法回复我的邮件。 这里是我的代码:使用EWS检查未读交换邮件的数量
[int]$nb_unread = 0
[string]$email = "[email protected]"
[string]$Msg = ""
[int]$Code = 0
[string]$err = ""
Try
{
Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
$ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013)
$ews.Credentials = New-Object Net.NetworkCredential('user', 'password')
$ews.AutodiscoverUrl($email, {$true})
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($ews,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
$view = new-object Microsoft.Exchange.WebServices.Data.ItemView(10)
$mailItems = $inbox.FindItems($view)
$mails | ForEach {$_.Load()}
foreach($mail in $mails)
{
if($mail.isread -eq $false)
{
nb_unread += 1
}
}
if (nb_unread -eq 0)
{
$Msg = "OK;No unread mail."
}
else
{
$Msg = ("NOOK;Unread mails : " -f $nb_unread)
}
}
Catch
{
$Code = 2
$Msg = ("CRITICAL: erreur(s) d'execution du script : {0}" -f $err)
}
当我的脚本执行 '$ mailItems = $ inbox.FindItems($视图)' 行,我得到这个错误。
Exception lors de l'appel de «FindItems» avec «1» argument(s): «The request failed. Le serveur distant a retourné une
erreur: (501) Non implémenté.»
Au caractère Ligne:16 : 5
+ $mailItems = $inbox.FindItems($view)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServiceRequestException
粗糙英文翻译
Exception when calling "FindItems" with "1" argument (s): "The request failed. The remote server returned an error: (501) Not implemented.
At Line:16 Char:5
+ $ mailItems = $inbox.FindItems ($ view)
+ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo: NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId: ServiceRequestException
答
A related question in C#开始了在同一只脚的你。您无需查询方框中的每封邮件,查看它是否未读。目前已有的信息对你的数据文件夹属性:UnreadCount
# Get the Mailbox ID of the Inbox folder.
$inboxFolderID = [Microsoft.Exchange.WebServices.Data.FolderId]::new([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailAddress)
# Bind to the inbox folder.
$boundFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($objExchange,$inboxFolderID)
$boundFolder.UnreadCount
在你的情况,你应该只需要使用$inbox.UnreadCount
并删除你的循环逻辑。
+0
谢谢, $ inbox.UnreadCount调用做我需要在我的脚本。 – Aurelien
答
我去了一个不同的形式给出:
$inbox_mails = $Inbox.FindItems($Inbox.TotalCount)
$inbox_mails | where-object IsRead -eq $false
然后通过管道,要么到格式表,或将其包装成().count
或做其他事吧。
像:
($inbox_mails | where-object IsRead -eq $false).count
而且,当贵$sfCollection
变量从何而来?
而你的问题是什么?这段代码如何不起作用?你有一个巨大的try块和没有catch块应该触发语法错误。代码是否从一个空的捕获中默默地错误? – Matt
那么,我的脚本执行FindItem时会崩溃。 我的消息更新了错误。 – Aurelien