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

new9mtju  于 2023-01-13  发布在  Shell
关注(0)|答案(1)|浏览(131)

我有一个工作脚本功能发送邮件它发送邮件时,需要。但需要修改它。
当一切正常时-只发送消息。当出错时-发送带附件的消息

$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"

在这个表格中附件总是被添加的。我需要改变什么才能达到目标?
花了很多时间和卡住。我知道如何做它与变量没有哈希表,但想尝试不修改整个函数,因为它。
任何帮助将不胜感激!

eblbsuwk

eblbsuwk1#

您不需要做太多更改,只需测试参数$Attachment是否有值,只有在给定值的情况下才将其添加到splatting Hashtable中
试试看

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"

相关问题