【问题标题】:Email attachment not saving correctly电子邮件附件未正确保存
【发布时间】:2019-01-21 18:48:41
【问题描述】:

每天早上我都会收到一封自动生成的电子邮件,其中包含一个 CSV 附件。这是我目前所拥有的:

$outlook = New-Object -ComObject Outlook.Application
$namespace = $outlook.GetNamespace("MAPI")
# Below: 6 is the default for inbox, so this saves the user from having to
# select the inbox folder. Change if emails w/ attatchements are going to a
# different folder
$folder = $namespace.GetDefaultFolder(6)
$filepath = "I:\PowerShell"
$folder.Items | foreach {
    $_.attachments | foreach {
        $filename = $_.filename
        if ($filename.Contains("example.csv")) {
            $_.SaveAsFile((Join-Path $filepath $filename))
            Rename-Item -LiteralPath '.\example.csv' -NewName "Server.csv" -Force
        }                     
    }
}

当我第一次运行时,它成功地从电子邮件中抓取附件,将附件保存到指定文件夹,并将其重命名为“Server.csv”。但是,当我第二次运行它时,它会抓取附件并保存它,但是它不会将其重命名/覆盖为“Server.csv”,因此它只会将其保存为 example.csv。它有时会抛出一个错误说

Rename-Item : 当文件已存在时无法创建文件

但是,我在那里有-Force,所以我不确定为什么会这样。

有什么建议吗?

【问题讨论】:

    标签: powershell csv outlook rename


    【解决方案1】:

    -Force 允许您重命名隐藏或只读的文件。它不允许您重命名文件以替换现有文件。检查目标文件是否已经存在,如果存在则将其删除。然后使用所需的文件名直接保存附件。

    $outfile = Join-Path $filepath 'Server.csv'
    if (Test-Path -LiteralPath $outfile) {
        Remove-Item $outfile -Force
    }
    $_.SaveAsFile($outfile)
    

    【讨论】:

      猜你喜欢
      • 2013-12-19
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 2021-06-26
      • 2012-02-01
      • 2019-05-07
      • 1970-01-01
      相关资源
      最近更新 更多