使用 Powershell 从 Outlook 下载时如何修复损坏的文件

How to fix corrupted files when download from outlook using powershell

我有一个 powershell 脚本,可以自动从 outlook 下载并保存在我已经设置的文件中。该脚本工作正常,但后来我意识到下载的某些附件已损坏。这是我使用的脚本。

Function saveattachmentexcel 
{
 $Null = Add-type -Assembly "Microsoft.Office.Interop.Outlook"
 #olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
 #olFolderInbox = 6
 $outlook = new-object -comobject outlook.application
 $namespace = $outlook.GetNameSpace("MAPI")
 $folder = $nameSpace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)
 $filepath = "D:\DMR Folder\"
 $folder.Items | Where {$_.UnRead -eq $True -and $($_.attachments).filename -match '.xlsm'} | ForEach-object {
      $filename = $($_.attachments | where filename -match '.xlsm').filename
    foreach($file in $filename)
    {
        $outpath = join-path $filepath $file
        $($_.attachments).saveasfile($outpath)
    }
     $_.UnRead = $False
   }
}
saveattachmentexcel

我不知道为什么会这样。谁能帮帮我?

这可能是因为您尝试使用 $($_.attachments).saveasfile($outpath) 语句将每个附件保存到磁盘上的同一文件名。

改变这个:

$filename = $($_.attachments | where filename -match '.xlsm').filename
foreach($file in $filename)
{
    $outpath = join-path $filepath $file
    $($_.attachments).saveasfile($outpath)
}

至:

foreach($attachment in $_.attachments)
{
    if($attachment.Filename -like '*.xlsm'){
        $outpath = Join-Path $filepath $attachment.Filename
        # Only save this particular attachment to disk - not all of them
        $attachment.SaveAsFile($outpath)
    }
}