Powershell 方法调用失败,因为[System.String]不包含名为';saveasfile';

Powershell 方法调用失败,因为[System.String]不包含名为';saveasfile';,powershell,outlook,Powershell,Outlook,我有一个powershell脚本,可以下载outlook邮件附件。 但我收到以下错误: 方法调用失败,因为[System.String]不包含名为“saveasfile”的方法 我用了下面的脚本 Add-Type -Assembly "Microsoft.Office.Interop.Outlook" $Outlook = New-Object -ComObject Outlook.Application $Namespace = $Outlook.GetNameSpace("MAPI") $i

我有一个powershell脚本,可以下载outlook邮件附件。 但我收到以下错误:

方法调用失败,因为[System.String]不包含名为“saveasfile”的方法

我用了下面的脚本

Add-Type -Assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
$inbox = $mapi.GetDefaultFolder(6)
$saveFilePath = "C:\temp\"
$subfolder = $inbox.Folders | Where-Object {$_.Name -eq “REPORTS”}

$mail = $subfolder.Items | Select-Object -Property Subject,SentOn,@{name="Attachments";expression={$_.Attachments|%{$_.DisplayName}}} | Where-Object{$_.attachments -match ".html" -and ($_.SentOn -gt '29-Oct-19 12:00:00 AM')} 

foreach ($email in $mail)
{
    if ($email.attachments.count -ge 1)
    {
        foreach ($attachment in $email.attachments)
        {
        $filename = $attachment.filename 
        $attachment.saveasfile((join-path $savefilepath $filename))
        }
    }
}

请告诉我如何解决此错误。

Outlook的
附件
属性的枚举器返回一个
字符串
键,而不是实际的附件对象(这就是为什么使用PowerShell之类的非类型或弱类型语言来处理COM是一个非常糟糕的主意)

虽然PowerShell希望被用作一种功能性的管道语言(这是一种需要调试的PITA),但有时使用老式的命令式代码更容易:

For( $i = 0; $i -le $email.Attachments.Count; $i++ ) {
    $attachment = $email.Attachments.Item( $i )
    $attachment.SaveAsFile( ( Join-Path $savefilepath $filename ) )
}

顺便说一句,您不需要
if($email.attachments.count-ge 1)
语句,因为($i=0;$i..循环也会检查
.Attachments.Count
属性。

您能否提供一种方法,让我可以从特定文件夹下载附件。因为在整个web上,这是我使用COM可以找到的唯一脚本。请帮助我out@EkanshSingh你可以使用我的答案中的代码和你现有的其他代码e、 只需替换foreach的外部
body($mail中的email)
loop。请帮助我,因为即使按照您的方式使用了loop,我也会遇到同样的错误mentioned@EkanshSingh我的代码不会出现相同的错误,因为我的代码不会将
$attachment
变成
字符串
值。如果看到完全相同的错误消息,则错误来自代码中的另一行,或者您正在运行另一个脚本文件而没有意识到它。在PowerShell ISE的调试器中运行脚本时会发生什么情况?