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

Checking number of unread exchange mails with EWS

我是 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\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

A related question in C# starts off on the same foot as you. You do not need to query every mail in the box to see if it is unread. There is a data folder property that already has that information for you: 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 并删除你的循环逻辑。

我采用不同的方法:

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

然后通过管道将其转换为 table 格式,或将其包装为 ().count 或对其执行其他操作。

喜欢:

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

还有,你的$sfCollection变量是从哪里来的?