脚本中的Try / Catch块无法正常工作

时间:2015-06-23 12:08:25

标签: powershell scripting

下面脚本的前提是我需要它来查看PDF格式的文件夹,这些文件夹将以其所针对的个人命名,然后将该名称与随附的CSV文件中的电子邮件相匹配并生成电子邮件它将适当的PDF发送给他们。

问题是我们的发送/接收限制为10MB,所以我一直试图找出一个try/catch块,如果某些PDF无法发送,会向某人发送电子邮件,但在其中&#39 ; s当前状态,如果遇到错误并且不向其他任何人发送消息,它似乎会停止脚本。

有人可以提供一些关于如何使其工作的建议,或者更好的解决方案吗?

我一直在查看do/while,看看我是否可以让它循环,直到发送的附件等于10MB,然后发送该消息并重新启动,但无法弄清楚。

非常感谢任何帮助,如果出现任何问题,请告诉我/您需要更多信息。

$CSV = Import-Csv "\\Server\Share\NamesAndEmails.csv"
$PDFFolder = "\\Server\Share\PDF Folder"

$ErrorActionPreference = "Continue"

ForEach($User in $CSV)
{
    $PDFs = Get-ChildItem -Path $PDFFolder | Where-Object { $_.Extension -eq ".pdf" -and $_.Name -like "*$($User.Name)*" }

    $to = $User.Email
    $from = "email@domain.com"
    $smtp = "smtp.domain.com"
    $body = "Please see attachments."
    $attachments = @()

    ForEach($PDF in $PDFs)
    {
        $attachments += $PDF.FullName
    }

    $MessageParameters = @{
        From = $from
        To = $to
        Subject = "Email subject"
        Body = $body
        SmtpServer = $smtp
        Attachments = $attachments
    } 

    try 
    { 
        Send-MailMessage @MessageParameters 
    } 
    Catch 
    {            
        Send-MailMessage `
            -smtp smtp.domain.com `
            -to "Name <email@domain.com>" `
            -from "Name <email@domain.com>" `
            -subject "Failed to send post for $($user.Name)" `
            -body "Please go to \\... and resend PDF's for $($user.name) across multiple messages as necessary." `
    }
}

0 个答案:

没有答案