如何使Send-MailMessage中的附件为可选?

时间:2019-06-28 15:06:28

标签: powershell

我在脚本中使用Send-MailMessage

Send-MailMessage -From 'User01 <user01@fabrikam.com>' -To 'User02 <user02@fabrikam.com>', 'User03 <user03@fabrikam.com>' -Subject 'Sending the Attachment' -Body 'Forgot to send the attachment. Sending now.' -Attachments .\data.csv -Priority High -DeliveryNotificationOption OnSuccess, OnFailure -SmtpServer 'smtp.fabrikam.com'

它很好用,除非有时无法创建日志文件(因此没有附件),否则Send-MailMessage无法发送电子邮件,因为附件不存在。 我如何才能将-attachment开关保留为Send-MailMessage的一部分,并且即使附件失败也仍会发送电子邮件?

类似这样的内容:-Attachments (mandatory=$false)$attachment

1 个答案:

答案 0 :(得分:1)

尽管我同意avic的观点,即使用飞溅是{$var|floor} 这样使用大量参数的cmdlet的方式,但也许还有另一种方法可以使格式保持完整。

Send-MailMessage参数的类型为string [](文件名数组),此外,它还可以通过管道传递到Send-MailMessage cmdlet。只要它是一个数组,即使数组为空,该cmdlet也可以正常使用。 您可以使用它来更改此命令:

-Attachments

如前所述,我个人更喜欢使用splatting