使用EWS检查未读交换邮件的数量

时间:2017-05-24 13:53:23

标签: powershell exchangewebservices powershell-v5.0

我是使用PowerShell的新手,目前正在编写一个脚本来检查共享邮箱是否包含未读邮件。 我目前正在尝试使用FindItems()方法收回邮件。 这是我的代码:

[int]$nb_unread = 0
[string]$email = "user@domain.org"
[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($ view)'行时出现此错误。

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

2 个答案:

答案 0 :(得分:2)

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并删除循环逻辑。

答案 1 :(得分:0)

我采取了不同的方式:

$inbox_mails = $Inbox.FindItems($Inbox.TotalCount)
$inbox_mails | where-object IsRead -eq $false

然后将其传输到格式表中,或将其包装到().count中或用它做其他事情。

像:

($inbox_mails | where-object IsRead -eq $false).count

此外,您的$sfCollection变量来自何处?