Send -MailMessage -Attachments will not accept null for any variables

孤街醉人 提交于 2019-12-12 03:38:32

问题


I'm using the Send-MailMessage function in Powershell v2.0 I'm using variables for the attachments as there will not always be attachments being sent. If there are no attachments (file locations) in the variables, I get an error otherwise it works. How I can I setup the Send-MailMessage function to output attachments and at other times not without it failing.

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

回答1:


You could use a "splat" parameter: a hash of {parameter name, parameter value} to avoid passing the Attachments parameter when not needed:

$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

(This ability to use a hash table to pass parameters was added in PowerShell V2.)




回答2:


assuming you wrote the function the easiest way is to put the variable for the attachmate last posh will accept leaving off if its the last one in the function call

it may not be fancy or correct but i have been using that method with an email function i wrote for a couple years now with no problem



来源:https://stackoverflow.com/questions/14560270/send-mailmessage-attachments-will-not-accept-null-for-any-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!