发送-MailMessage -Attachments不会对任何变量接受null

时间:2013-01-28 10:45:15

标签: powershell powershell-v2.0

我正在使用Powershell v2.0中的Send-MailMessage函数我正在为附件使用变量,因为不会总是发送附件。如果变量中没有附件(文件位置),我会收到错误,否则它会起作用。如何设置Send-MailMessage函数以输出附件,有时则不会失败。

Send-MailMessage -BodyAsHtml –From Monitoring@CorporateActions -Priority $Priority –To "steven.meadows@dionglobal.eu" -Attachments $IDCSwiftLogFileAttachment,$SecurityLogFileAttachment, $ClientTypeLogFileAttachment –Subject “Corporate Actions Overnight Processing” –Body "<b><u> Download Status: </u></b> <br><br> $SWIFTDownloadErrorMessage $SecurityDownloadErrorMessage $ClientDownloadErrorMessage $HoldingDownloadErrorMessage $CLISLOOKDownloadErrorMessage $SWIFTDownloadSuccessMessage $SecurityDownloadSuccessMessage $ClientDownloadSuccessMessage $HoldingDownloadSuccessMessage $CLISLOOKDownloadSuccessMessage <b><u> X-Gen Processing Status: </u></b> <br><br> $SWIFTXGenNoInputMessage $SecurityXGenNoInputMessage $ClientXGenNoInputMessage $HoldingXGenNoInputMessage $CLISLOOKXGenNoInputMessage $IDCSwiftXGenSuccessMessage $SecurityXGenSuccessMessage $ClientXgenSuccessMessage $HoldingXgenSuccessMessage $ClientTypeXGenSuccessMessage $IDCSwiftXgenErrorMessage $SecurityXgenErrorMessage $ClientXgenErrorMessage $HoldingXgenErrorMessage $ClientTypeXGenErrorMessage”  –SmtpServer smtp.investmaster.com

2 个答案:

答案 0 :(得分:2)

您可以使用“splat”参数:{参数名称,参数值}的哈希值,以避免在不需要时传递Attachments参数:

$attachments = @()
if ($IDCSwiftLogFileAttachment) {
  $attachments += $IDCSwiftLogFileAttachment
}
# Repeat for each potential parameter

$params = @{}
if ($attachments.Length -gt 0) {
  $params['Attachments'] = $attachments
}

Send-MailMessage @params -BodyAsHtml –From Monitoring@CorporateActions -Priority $Priority # Other parameters

(在PowerShell V2中添加了使用哈希表传递参数的功能。)

答案 1 :(得分:0)

假设您编写函数最简单的方法是将变量放在最后 如果它是函数调用中的最后一个

,它将接受离开

它可能不是花哨或正确但我一直使用该方法与我写了几年的电子邮件功能现在没有问题