首页 > 解决方案 > 如何在 Powershell 中使用 Get-ChildItem 将文件附加到电子邮件

问题描述

我正在尝试编写执行以下操作的 Powershell 脚本:

  1. 检查目录中的所有文件以获取有效字符串
  2. 获取包含该有效字符串的每个文件,然后将它们作为电子邮件附件发送

我不在乎是否发送一封包含所有有效文件的电子邮件,或者是否为每个有效文件发送一封电子邮件。

以下代码是我所拥有的,但在尝试附加文件时出错,说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
}

任何帮助是极大的赞赏。

标签: powershellemail-attachments

解决方案


首先,确保$ValidFiles仅包含字符串(文件路径):

$ValidFiles = Get-ChildItem -Path C:\Results -Recurse | 
                Select-String -List -Pattern "Test" | 
                  ForEach-Object Path
  • 添加-ListtoSelect-String使搜索在给定文件中找到的第一个匹配项处停止,这消除了对Select-Object -Unique.

  • Select-Object输出[pscustomobject]具有指定属性的实例,即使只指定了一个属性Path;虽然您可以-ExpandProperty Path改为仅获取.Path属性,但使用ForEach-Object属性名称更简单。

然后,使用$ValidFile- 现在是路径字符串- 直接作为-Attachments参数(它是[string[]]-typed,但也接受标量[string]实例(单个字符串))。

  • 通常,不要使用Out-String除非您想要格式化以显示输入对象的表示形式。

推荐阅读