通过Powershell将多个附件添加到带有txt文件路径的电子邮件中



使用powershell,我想扫描一个包含多个txt文件(备份日志文件(的文件夹,如果发生错误,请创建一封电子邮件,其中包含包含附加到邮件的错误消息的特定txt文件。

目前,我识别日志文件并将其路径写入单独的txt文件。

Get-ChildItem $pfad -Filter *Error*.txt -Recurse | Select-String "Error occured" | Select-Object -expandproperty Path | Out-File -FilePath $filelist

我得到一个包含这个的txt文件(没有标题,没有空行(:

D:Sharetest2Neues TextdokumentError.txt
D:Sharetest2Testfile fbibgfwErroriebgfvibfvsbvf full.txt

然后我想创建一封电子邮件并附加该单独的 txt 文件中的文件。

$logfiles = Get-Content $filelist
ForEach($log in $logfiles)
  {
  Write-Host “Attaching File :- ” $log
  $attachment = New-Object System.Net.Mail.Attachment –ArgumentList $log
  $msg.Attachments.Add($attachment)
  }

这是我不断得到的结果:

Attaching File :-  D:Sharetest2Neues TextdokumentError.txt
Es ist nicht möglich, eine Methode für einen Ausdruck aufzurufen, der den NULL hat.
In C:testUnbenannt1.ps1:43 Zeichen:3
+   $msg.Attachments.Add($attachment)
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
Attaching File :-  D:Sharetest2Testfile fbibgfwErroriebgfvibfvsbvf full.txt
Es ist nicht möglich, eine Methode für einen Ausdruck aufzurufen, der den NULL hat.
In C:testUnbenannt1.ps1:43 Zeichen:3
+   $msg.Attachments.Add($attachment)
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

在英语中,错误的意思是:"无法为具有 NULL 的表达式调用方法。

显示的路径是正确的,文件在那里并且它们有内容。

感谢您的帮助!

您的文件路径中似乎有空格。如果在定义$attachment时将"$log"放在引号中会发生什么?

更好的解决方案:为了避免在解析文本文件中的字符串时大惊小怪,请不要将文件列表输出为文本。只需使用文件系统对象。

$logfiles = Get-ChildItem $pfad -Filter *Error*.txt -Recurse | Select-String "Error occured" -List | Select Path

(未测试,因此请检查命令返回您要查找的文件(

最新更新