【问题标题】:How to attach files to email using Get-ChildItem in Powershell如何在 Powershell 中使用 Get-ChildItem 将文件附加到电子邮件
【发布时间】:2020-03-02 01:17:18
【问题描述】:

我正在尝试编写执行以下操作的 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
}

非常感谢任何帮助。

【问题讨论】:

    标签: powershell email-attachments


    【解决方案1】:

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

    $ValidFiles = Get-ChildItem -Path C:\Results -Recurse | 
                    Select-String -List -Pattern "Test" | 
                      ForEach-Object Path
    
    • -List 添加到Select-String 会使搜索停止在给定文件中找到的第一个 匹配项,这样就不需要Select-Object -Unique

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

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

    • 一般情况下,不要使用Out-String,除非您想要格式化为显示输入对象的表示。

    【讨论】:

      【解决方案2】:

      Out-string 阻止 $Attachment 被填充。

      $Attachment = $ValidFile | Out-String
      

      试试

       $Attachment = $ValidFile
      

      【讨论】:

      • 这仍然会引发相同的错误。我最初添加了 Out-String,因为它会抛出一个错误,如“Cannot have type Object requires type String[]”
      猜你喜欢
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2011-05-07
      • 2020-01-14
      • 1970-01-01
      • 2014-06-25
      • 1970-01-01
      相关资源
      最近更新 更多