You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PowerShell邮件脚本添加多位置附件的正确语法咨询

正确使用Send-MailMessage添加多个不同位置附件的语法

嘿,这个场景我太熟悉了!其实PowerShell里Send-MailMessage-Attachments参数设计得很灵活,完全支持添加不同位置的多个附件,核心语法就是用逗号把各个文件路径(不管是变量还是直接写的字符串)分隔开就行,一点都不复杂。

我给你分几种常用场景举例:

1. 结合现有变量 + 新增不同位置的文件

你已经定义了两个文件变量:

$Report = "C:\somefolder\somefile.xml"
$AnotherReport = "C:\somefolder\someotherfile.xml"

如果要再加一个D盘路径下的文件(比如D:\anotherpath\thirdfile.pdf),直接把它和现有变量用逗号隔开传给-Attachments就好:

Send-MailMessage -To "recipient@example.com" `
                 -From "sender@example.com" `
                 -Subject "批量报告附件" `
                 -SmtpServer "smtp.yourdomain.com" `
                 -Attachments $Report, $AnotherReport, "D:\anotherpath\thirdfile.pdf"

2. 直接传入多个不同位置的路径字符串

如果不想用变量,直接把所有文件的完整路径用逗号分隔就行,不管它们在哪个盘哪个文件夹:

Send-MailMessage -Attachments "C:\somefolder\somefile.xml", "E:\docs\annual-report.xlsx", "F:\backup\log.txt" `
                 <其他必要参数(收件人、发件人、SMTP服务器等)>

3. 用数组变量管理大量附件

如果要添加的附件特别多,可以先把所有路径放进一个数组变量里,再传给参数,这样代码更整洁:

# 把所有不同位置的附件路径放进数组
$allAttachments = @(
    $Report,
    $AnotherReport,
    "D:\anotherpath\thirdfile.pdf",
    "E:\docs\annual-report.xlsx"
)

# 发送邮件时直接传入数组
Send-MailMessage -Attachments $allAttachments `
                 -To "recipient@example.com" `
                 -From "sender@example.com" `
                 -Subject "多附件邮件" `
                 -SmtpServer "smtp.yourdomain.com"

小提醒

一定要确认每个文件的路径都是正确的,并且运行脚本的用户有读取这些文件的权限,不然会抛出“找不到文件”的错误。如果想更稳妥,可以提前加个文件存在性检查:

$allAttachments = @($Report, $AnotherReport, "D:\anotherpath\thirdfile.pdf")

foreach ($file in $allAttachments) {
    if (-not (Test-Path -Path $file -PathType Leaf)) {
        Write-Warning "警告:文件不存在或不是文件:$file,将跳过该附件"
        # 从数组中移除不存在的文件
        $allAttachments = $allAttachments | Where-Object { $_ -ne $file }
    }
}

# 确认有有效附件再发送
if ($allAttachments.Count -gt 0) {
    Send-MailMessage -Attachments $allAttachments <其他必要参数>
} else {
    Write-Error "没有可用的附件,终止发送"
}

内容的提问来源于stack exchange,提问作者Christopher Mellor

火山引擎 最新活动