简体   繁体   English

通过哈希表在 Send-MailMessage 函数中添加附加参数附件

[英]Add aditional parameter attachment in Send-MailMessage function via hashtable

i have a working script with function SendMsg It send mail when is require.我有一个具有 SendMsg 功能的工作脚本,它在需要时发送邮件。 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!任何帮助,将不胜感激!

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您不需要做太多更改,只需测试您的参数$Attachment是否具有值,并且仅在给定值时才将其添加到 splatting Hashtable

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM