【问题标题】:Microsoft Graph API - Powershell - Retrieve Excel file attachmentMicrosoft Graph API - Powershell - 检索 Excel 文件附件
【发布时间】:2022-01-06 14:26:44
【问题描述】:

我正在使用 Microsoft Graph API 来检索邮件中的附件。

我使用这个端点来检索附件 https://graph.microsoft.com/v1.0/users/{mailbox.mail}/messages/{message.id}/attachments/

$callAPI = @{
  Headers = @{
      Authorization = "Bearer $token"
  }
  Uri = "https://graph.microsoft.com/v1.0/users/{mailbox.mail}/messages/{message.id}/attachments/"
  Method = "GET"
}

$attachments = (Invoke-RestMethod @callAPI).value;

在我使用 foreach 通过此端点检索附件内容后: https://graph.microsoft.com/v1.0/users/{mailbox.mail}/messages/{message.id}/attachments/{attachment.id}/$value

$callAPI = @{
   Headers = @{
     Authorization = "Bearer $token"
   }
   Uri = "https://graph.microsoft.com/v1.0/users/{mailbox.mail}/messages/{message.id}/attachments/{attachment.id}/$value"
   Method = "GET"
}

$content = Invoke-RestMethod @callAPI;

我使用这个命令行来保存文件:

Set-Content -Path "$($attachmentsTempDestination)\$($attachment.name)" -Value $content

但我的文件有问题,Excel 无法识别。

我在 PostMan 中尝试附件内容的端点并保存响应(图片:PostMan save response)。保存的文件是正确的。

可能是我最后一次保存内容的 PowerShell 命令不好,但我不知道如何解决这个问题。

请帮帮我!


有了@glen-scales 的回答,我为我的用例找到了一个很好的 PowerShell 代码:

  $callAPI = @{
      Headers = @{
          Authorization = "Bearer $token"
      }
      Uri = "https://graph.microsoft.com/v1.0/users/{mailbox.mail}/messages/{message.id}/attachments/"
      Method = "GET"
    }

$attachments = (Invoke-RestMethod @callAPI).value;

foreach ($attachment in $attachments) {     

[System.IO.File]::WriteAllBytes("$($attachmentsTempDestination)\$($attachment.name)",[System.Convert]::FromBase64String($attachment.contentBytes)) 
    
}

【问题讨论】:

  • {mailbox.mail}{message.id}{attachment.id} 未在您在此处提供的内容中定义。这应该像使用 $token 一样使用变量来定义。

标签: powershell api microsoft-graph-api attachment


【解决方案1】:

附件内容是一个 base64 编码的字符串,因此您使用 set-content 的方式只会将该 base64 内容写入无效的文件。

您需要先将其转换为字节数组,然后您应该能够执行类似的操作

Set-Content -Path "$($attachmentsTempDestination)\$($attachment.name)" -Value [System.Convert]::FromBase64String($content) -Encoding Byte

否则你也可以使用(可能比 set-content 更快)

[System.IO.File]::WriteAllBytes("$($attachmentsTempDestination)\$($attachment.name)",[System.Convert]::FromBase64String($content))

【讨论】:

  • 感谢@glen-scales,答案很好,但最后一个端点的返回值不是 Base64 格式。但我使用第一个端点和 $attachment.contentBytes 没关系。非常感谢你
猜你喜欢
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多