如何通过哈希表为Send-MailMessage函数按需添加附件参数
修改方案
核心思路
利用哈希表的动态特性,只在需要时(传入-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" # 关联Message参数作为邮件正文 Body = $Message } # 关键:仅当Attachment参数有有效值时,才往哈希表添加附件配置 if (-not [string]::IsNullOrEmpty($Attachment)) { $mailParams["Attachments"] = $Attachment # 如需支持多个附件,可改为 $mailParams["Attachments"] = $Attachment.Split(';') } Send-MailMessage @mailParams } # 错误场景:传入附件路径和错误消息 SendMsg -Attachment "c:\tmp\1.txt" -Message "Error" # 正常场景:仅发送消息 SendMsg -Message "All Good"
主要修改点
- 修正参数定义的语法错误:两个参数之间添加逗号(原代码缺逗号会触发语法报错)
- 移除原代码中硬编码的附件添加逻辑,改为条件判断:只有当
$Attachment参数不为空时,才将附件路径加入$mailParams哈希表 - 调用时直接传入实际的附件路径(原代码中
$Attach是$mailParams.Add()的返回值,实际为$null,完全无效) - 补充
Body参数关联$Message,确保消息内容能作为邮件正文发送(原代码未配置Body,消息内容不会显示在邮件里)
额外说明
如果需要支持多个附件,可以调整参数逻辑:
# 方案1:将参数改为数组类型 [Parameter(Mandatory=$False)][String[]]$Attachment # 方案2:保持字符串参数,调用时用分号分隔多个路径,内部拆分 if (-not [string]::IsNullOrEmpty($Attachment)) { $mailParams["Attachments"] = $Attachment.Split(';') | Where-Object { $_ } }
内容的提问来源于stack exchange,提问作者Gsser
相关产品推荐
相关产品推荐

