发送邮件消息失败,因为附件丢失(混乱变量)

时间:2012-01-19 22:08:48

标签: variables powershell

我发送了一堆文件作为附件Send-MailMessage 有些文件存在,有些文件没有,因此如果缺少其中一个文件,则Send-MailMessage会失败。

如果文件丢失,我有办法Test-Path并清理$attachments吗?

我的代码:

$Attachments = "$longlist_file","$PingList_File","$quicklist_file", `
  "$nConf_import_host_file","$nConf_import_service_file", `
  "$nconf_export_host_file","$nconf_export_service_file"

# Sending mail
send-mailmessage -to $ToAddress -from $FromAddress -smtpserver $SMTPServer `
  -subject $MessageSubject -Body $MessageBody -Attachments $Attachments

4 个答案:

答案 0 :(得分:6)

可能

$Attachments = $longlist_file","$PingList_File","$quicklist_file", `
  "$nConf_import_host_file", "$nConf_import_service_file", `
  "$nconf_export_host_file", "$nconf_export_service_file" `
  | Where-Object { Test-Path $_ }

答案 1 :(得分:2)

创建一个仅包含存在的文件的新列表:

$realFiles = $Attachments | ? {Test-Path -Path $_}

然后发送。

send-mailmessage -to $ToAddress -from $FromAddress -smtpserver $SMTPServer -subject $MessageSubject -Body $MessageBody -Attachments $realFiles 

答案 2 :(得分:0)

这样的事情可以解决问题:

$Attachments = @("$longlist_file","$PingList_File","$quicklist_file","$nConf_import_host_file","$nConf_import_service_file","$nconf_export_host_file","$nconf_export_service_file")
$TestedAttachments = @()
foreach($file in $Attachments)
{
    try
    {
        $file = get-content -path $file
        write-host "File $($file) exists, adding to tested list"
        $TestedAttachments += $file
    }
    catch[system. exception]
    {
        write-host "File $(file) was not found."
    }
}
send-mailmessage -to $ToAddress -from $FromAddress -smtpserver $SMTPServer -subject $MessageSubject -Body $MessageBody -Attachments $TestedAttachments

问候 Arcass

答案 3 :(得分:0)

get-childitem $attachments -ea 0 | send-mailmessage......