将 Microsoft Graph 中的电子邮件附件输出到磁盘上的文件中

Outputting an email attachment from Microsoft Graph into a file on disk

我使用 Microsoft Graph 的 REST API 从电子邮件对象中检索了一些附件,因此:

$Header = Get-Header -theRequest $Credential
$restUrl = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/messages/$messageId/attachments"
$emailAttachmentResult = Invoke-RestMethod -Uri $restUrl -Headers $Header -Method Get -ContentType "application/json"

我可以 [然后] 成功循环这​​些附件结果:

foreach($att in $emailAttachmentResult.value)
{
    $attName = $att.Name
    Write-Output $attName  # Successfully displays the name of the attachment
}

我接下来要做的是将这个附件的内容输出到磁盘上的一个文件中。这就是我卡住的部分。

我尝试了各种复杂的方法 - 这是我最近的尝试[失败了 - 它只是创建了零长度的文件]:

$theFolderToUse = "C:\temp"
$filename = (Join-Path $theFolderToUse $att.Name.ToString())
[System.IO.File]::Create($filename)
[System.IO.File]::WriteAllBytes($filename, $att.ContentBytes)

我也试过这个:

$attachmentContent = $att.ContentBytes
$fiFile = New-Object System.IO.FileStream((Join-Path $theFolderToUse $att.Name.ToString()), [System.IO.FileMode]::Create)
$fiFile.Write($attachmentContent, 0, $attachmentContent.length)

但这也会输出零长度文件。

我进一步尝试转换变量:

$att.ContentBytes

字节数组因此:

$converter = [System.Text.Encoding]::Unicode
$byteArray = $converter.GetBytes($attachmentContent);
$fiFile = New-Object System.IO.FileStream((Join-Path $theFolderToUse $att.Name.ToString()), [System.IO.FileMode]::Create)
$fiFile.Write($byteArray, 0, $byteArray.length)

这会输出包含内容但格式不可读的文件。以某种方式存在的数据:

$att.ContentBytes

没有通过来回转换过程使其真正重构原始文件附件...

任何人都可以建议如何获得:

$att.ContentBytes

写入磁盘上的文件?请记住,所显示的附件包括二进制文件,如 PDF 和 Excel 电子表格。

谢谢大家,

大卫 :-)

ContentBytes 是用 Base64 编码的,因此您首先需要将其转换为字节数组,然后将该字节数组写入文件,例如

    $downloadDirectory = "c:\temp"
    foreach($att in $emailAttachmentResult.value)
    {
        $fiFile = new-object System.IO.FileStream(($downloadDirectory  + "\" + $att.Name.ToString()), [System.IO.FileMode]::Create)
        $attachBytes = [System.Convert]::FromBase64String($att.ContentBytes)   
        $fiFile.Write($attachBytes, 0, $attachBytes.Length)
        $fiFile.Close()
    }