powershell - 无法使用 Send-MailMessage 从不同目录发送多个附件
问题描述
如果这些文件位于不同的目录中,我无法使用Send-MailMessage
cmdlet发送多个附件。我可以发送一个文件,我可以发送另一个文件,如果它们在同一个目录中,我可以发送两者,但如果它们在不同的目录中,则不能。
文件/文件夹如下所示:
C:\Scripts\Folder\test.txt
C:\Scripts\Folder\Logs\log.txt
我通过创建这样的数组将这些文件指定为附件:
$attachments = @("C:\Scripts\Folder\test.txt","C:\Scripts\Folder\Logs\log.txt")
我正在运行 PowerShell 5.1,并已在 Windows Server 2012 R2 和 Windows 10 v1803 上对此进行了测试。
Windows Server 2012 R2 上的 $PSVersionTable:
Name Value
---- -----
PSVersion 5.1.14409.1018
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.14409.1018
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Windows 10 1803 上的 $PSVersionTable:
Name Value
---- -----
PSVersion 5.1.17134.407
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17134.407
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
这是发送消息的完整脚本:
# Credentials
$username = "user@domain.com"
$password = ConvertTo-SecureString -String "password" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password
# Attachments
$attachments = @("C:\Scripts\Folder\test.txt","C:\Scripts\Folder\Logs\log.txt")
Send-MailMessage -To "Recipient <recipient@domain.com>" -Subject "Subject Line" -Body "Body text" -SmtpServer smtp.domain.com -Attachments $attachments -Credential $cred -From "Sender <user@domain.com>" -Port 587 -Priority High -UseSsl
没有产生错误消息,并且该消息与第一个附件一起发送和传递。如果我从数组中删除第一个文件,则发送第二个文件(较低目录中的文件)。如果我将第二个文件移动到与第一个文件相同的目录,则两者都可以正常发送。我一直在寻找关于为什么会发生这种情况的答案,但我找不到关于为附件提供多个目录的问题的答案。Send-MailMessage 的帮助中也没有指定关于多个目录的任何内容。
我也尝试过以不同的方式指定附件文件。我试过了:
- 将每个文件的 FullName 添加到其自己的变量中,并制作
$attachments
这些变量的数组 - 使用
Get-ChildItem -Recurse | Where-Object {($_.Name -eq "test.txt") -or ($_.Name -eq "log.txt")} | Send-MailMessage
除非两个文件都在同一个目录中,否则这些都不起作用。谁能帮助解释为什么会这样或告诉我我哪里出错了?我知道有很多解决方法,但我想解决这个特定问题。
解决方案
我刚刚使用您的代码进行了测试,并在我的 Windows 10 机器上重新创建了相同的文件夹/文件结构,一切都按预期工作。
我收到了电子邮件,两个附件都存在。
你$PSVersionTable
说你的 PowerShell 的 PSVersion 是什么?
我的是这样的:
Name Value
---- -----
PSVersion 5.1.17763.134
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.17763.134
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
这是运行 Windows 10 build 1809 对于我的测试,我使用我的 Office 365 帐户通过 smtp.office365.com 发送。
推荐阅读
- anylogic - Anylogic中代理的默认属性是什么?复制代理的正确方法是什么?
- firebase - 如何在flutter中避免第一次从firestore中满载内容
- error-handling - 我如何在代码中正确使用 >= 和 <=?
- c# - Automapper IEnumerable
类的未映射 - java - 在该方法中添加新参数时如何模拟该方法?
- laravel - 我的heroku部署出了什么问题?
- amazon-web-services - 我是否需要设置 Glacier Vault 来归档 S3 中的数据?
- sentry - 是否可以将其他属性传递给 Sentry 用户反馈报告?
- postgresql - 带有 uuid 的递归分层 PGSQL 请求进入循环
- performance - 性能分析服务结构依赖应用程序