Cataster
Cataster

Reputation: 3481

How to make attachment in Send-MailMessage optional?

I amd using Send-MailMessage in my script

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

it works great, except sometimes when a log file fails to get created, thus no attachment, Send-MailMessage fails to send an email because attachment is not there. how can i keep the -attachment switch as part of Send-MailMessage and still send email even if somehow the attachment fails?

something like this: -Attachments (mandatory=$false)$attachment

Upvotes: 0

Views: 1340

Answers (1)

Theo
Theo

Reputation: 61028

Although I agree with avic that using splatting is the way to go with cmdlets like Send-MailMessage that use a lot of parameters, there may also be another way, keeping your format sort-of intact.

The -Attachments parameter is of type string[] (an array of file names) and what's more, it can be piped to the Send-MailMessage cmdlet. As long as it is an array, the cmdlet seems fine with it, even if the array is empty. You could use that to change the command you have to this:

# see if the file to attach is there and if not make $attachments an empty array
if (Test-Path -Path '.\data.csv' -PathType Leaf) { $attachments = @('.\data.csv') } else { $attachments = @() }

# pipe the attachments array to the cmdlet
$attachments | Send-MailMessage -From 'User01 <[email protected]>' -To 'User02 <[email protected]>', 'User03 <[email protected]>' -Subject 'Sending the Attachment' -Body 'Forgot to send the attachment. Sending now.' -Priority High -DeliveryNotificationOption OnSuccess, OnFailure -SmtpServer 'smtp.fabrikam.com'

As said, personally I would prefer using splatting for this..

Upvotes: 1

Related Questions