Microsoft Graph PowerShell脚本未读邮件附件打印筛选功能故障
问题描述
开发了一款连接Microsoft Graph的PowerShell脚本,用于打印共享邮箱收件箱中未读邮件的附件。目前脚本其他功能(如下载附件、打印、标记已读)均正常,但筛选未读邮件的功能失效,无法只获取未读邮件。疑似问题出在邮件查询的URL行:
$mailUrl = "https://graph.microsoft.com/v1.0/users/$sharedMailbox/mailFolders/inbox/messages?$filter=isRead -eq $false"
问题原因
Microsoft Graph的OData筛选器语法有两个关键要求:
- 布尔值比较需使用小写的
false(API对布尔值大小写敏感) - 比较运算符为
eq(而非PowerShell的-eq)
原脚本错误混用了PowerShell语法和Graph API的OData语法,导致筛选条件不被识别,返回了收件箱所有邮件而非仅未读邮件。
修复方案
修正查询URL的筛选条件,符合OData规范:
- 将
-eq替换为eq - 确保
false为小写 - 在PowerShell中用反引号
`转义$符号,避免被当作变量解析
修正后的URL行:
$mailUrl = "https://graph.microsoft.com/v1.0/users/$sharedMailbox/mailFolders/inbox/messages`$filter=isRead eq false"
完整修正后的脚本
# Install Microsoft Graph PowerShell module if not already installed if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) { Install-Module Microsoft.Graph -Scope CurrentUser -Force } # Define Azure App Credentials $tenantId = "0000000000000000000000000000" $clientId = "000000000000000000000000000000000" $clientSecret = "00000000000000000000000000000000000" $sharedMailbox = "emailtester@abccorp.com" # Get Access Token $body = @{ grant_type = "client_credentials" client_id = $clientId client_secret = $clientSecret scope = "https://graph.microsoft.com/.default" } $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -Body $body $accessToken = $tokenResponse.access_token # Fetch Emails from Shared Mailbox $headers = @{ Authorization = "Bearer $accessToken" "Content-Type" = "application/json" } # 修正后的筛选未读邮件URL $mailUrl = "https://graph.microsoft.com/v1.0/users/$sharedMailbox/mailFolders/inbox/messages`$filter=isRead eq false" $mails = Invoke-RestMethod -Uri $mailUrl -Headers $headers -Method Get # Loop through emails and process attachments foreach ($mail in $mails.value) { $mailId = $mail.id $attachmentsUrl = "https://graph.microsoft.com/v1.0/users/$sharedMailbox/messages/$mailId/attachments" $attachments = Invoke-RestMethod -Uri $attachmentsUrl -Headers $headers -Method Get foreach ($attachment in $attachments.value) { if ($attachment."@odata.type" -eq "#microsoft.graph.fileAttachment") { $fileName = $attachment.name $fileContent = [System.Convert]::FromBase64String($attachment.contentBytes) $filePath = "$env:TEMP\$fileName" # Save attachment [System.IO.File]::WriteAllBytes($filePath, $fileContent) Write-Output "Downloaded: $filePath" # Print the file Start-Process -FilePath $filePath -Verb Print } } # Mark email as read $markAsReadUrl = "https://graph.microsoft.com/v1.0/users/$sharedMailbox/messages/$mailId" $markAsReadBody = @{ isRead = $true } | ConvertTo-Json Invoke-RestMethod -Uri $markAsReadUrl -Headers $headers -Method Patch -Body $markAsReadBody } Write-Host "Processing Completed"
内容的提问来源于stack exchange,提问作者Matt Springer
相关产品推荐
相关产品推荐

