Search code examples
powershellparametershashtablesendmailattachment

Add aditional parameter attachment in Send-MailMessage function via hashtable


i have a working script with function SendMsg It send mail when is require. However require to modify it.

When everything is good - send only a message. When error - send a message with attachment

$recipients = "test@eva.com","test2@eva.com"

function SendMsg() {
    param(
    [Parameter(mandatory=$False)][AllowEmptyString()][String]$Message
    [Parameter(mandatory=$False)][AllowEmptyString()][String]$Attachment
        
    )
   
    $mailParams = @{
        from       = "Boss@eva.com"
        to         = $recipients.Split(';')
        subject    = "PWE script"
        smtpserver = "mailer.eva.com"
        
    }
    $Attach = $mailParams.Add("Attachments","c:\tmp\1.txt")
    
    
    Send-MailMessage @mailParams
}
__________________________________

#Error in the script bellow
SendMsg -Attachment $Attach -message "Error"

#As expect
SendMsg -message "All Good"

In this form attachment is added always. What do i need to change to reach the goal?

Spent a lot of time and stuck. I know how to do it with variables without hashtable, however wanna try not modified whole function because of it.

Any help would be appreciated!


Solution

  • You don't need to change much, simply test if your parameter $Attachment has a value or not and only add it to the splatting Hashtable if there is some value given

    Try

    function SendMsg() {
        param(
            [Parameter(Mandatory = $true)]  # there must at least be one recipient
            [ValidateNotNullOrEmpty()]
            [string[]]$To,
    
            # the other parameters are optional and $null by default
            [String]$Message = $null,
            [String[]]$Attachment = $null  # [string[]] to allow for an array of attachments
        )
    
        $mailParams = @{
            from       = "Boss@eva.com"
            to         = $To
            subject    = "PWE script"
            body       = $Message
            smtpserver = "mailer.eva.com"
        }
        # test if the Attachment array has values and only then add it to the Hashtable
        if ($Attachment.Count -gt 0) {
            $mailParams['Attachments'] = $Attachment
        }
    
        Send-MailMessage @mailParams
    }
    
    
    # send your email
    SendMsg -To "test@eva.com", "test2@eva.com" -Attachment "c:\tmp\1.txt" -Message "Should be fine"