1
votes

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 "[email protected]" -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

2 Answers

3
votes

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.)

0
votes

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