powershell - 如何在 Powershell 中使用 Get-ChildItem 将文件附加到电子邮件
问题描述
我正在尝试编写执行以下操作的 Powershell 脚本:
- 检查目录中的所有文件以获取有效字符串
- 获取包含该有效字符串的每个文件,然后将它们作为电子邮件附件发送
我不在乎是否发送一封包含所有有效文件的电子邮件,或者是否为每个有效文件发送一封电子邮件。
以下代码是我所拥有的,但在尝试附加文件时出错,说Send-MailMessage :找不到驱动器。名为 ' 的驱动器
$ValidFiles = Get-ChildItem -Path C:\Results -Recurse |
Select-String -Pattern "Test" |
Select-Object -Unique Path
foreach ($ValidFile in $ValidFiles)
{
$From = 'test <test@test.com>'
$To = 'me <me@test.com>'
$Subject = "Valid File Found"
$Username = "Test-Domain\test"
$Password = ConvertTo-SecureString "notrealpassword" -AsPlainText -Force
$Creds = New-Object System.Management.Automation.PSCredential($username, $password)
$Body = "Please review the attached files"
$Attachment = $ValidFile | Out-String
$SMTPServer = "test-com.mail.protection.outlook.com"
Send-MailMessage -From $From -To $To -Subject $Subject -Credential ($Creds) -Attachments $Attachment -UseSsl -Body $Body -DeliveryNotificationOption OnSuccess, OnFailure -SmtpServer $SMTPServer
}
任何帮助是极大的赞赏。
解决方案
首先,确保$ValidFiles
仅包含字符串(文件路径):
$ValidFiles = Get-ChildItem -Path C:\Results -Recurse |
Select-String -List -Pattern "Test" |
ForEach-Object Path
添加
-List
toSelect-String
使搜索在给定文件中找到的第一个匹配项处停止,这消除了对Select-Object -Unique
.Select-Object
输出[pscustomobject]
具有指定属性的实例,即使只指定了一个属性Path
;虽然您可以-ExpandProperty Path
改为仅获取.Path
属性值,但使用ForEach-Object
属性名称更简单。
然后,使用$ValidFile
- 现在是路径字符串- 直接作为-Attachments
参数(它是[string[]]
-typed,但也接受标量[string]
实例(单个字符串))。
- 通常,不要使用,
Out-String
除非您想要格式化以显示输入对象的表示形式。
推荐阅读
- c# - 使用 IEnumerable 从连接中返回 IQueryable
- spring-boot - 如何使用springboot将所有微服务日志记录在一个日志文件中
- microcontroller - 在 I2C 总线中,从设备如何知道数据是否属于它们
- javascript - iFrame 中 Firefox 上的麦克风权限不是永久性的
- spring - Keycloak - 找不到指定孩子的公钥
- java - 断言对象是一个有效的顶级 json 可序列化
- google-cloud-platform - 当我使用 Google Cloud Application Flex 提供的 Memcache 服务时,“session_memcached_host:”会是什么。引擎?
- angular - 具有延迟加载和子路由设置的 Angular
- javascript - matter.js 物理引擎中的结果总是不同的
- android - java.lang.NullPointerException:空对象引用上的 FloatingActionButton.setVisibility(int)'