简体   繁体   中英

Adding multiple attachments to email with paths from txt file via powershell

Using powershell I want to scan a folder containing several txt-files (backup logfiles) and in case of an error create an email with the specific txt-files containing the error messages attached to the mail.

at the moment I identify the logfiles and write their path to a seperate txt-file.

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

I get a txt file containing this (no headers, no blank lines):

D:\Share\test2\Neues TextdokumentError.txt
D:\Share\test2\Testfile fbibgfwErroriebgfvibfvsbvf full.txt

Then I want to create an e-mail and attach the files from that seperate txt-file.

$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)
  }

This is the result I keep getting:

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

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

In english the error means: "It is not possible to call a method for an expression that has the NULL."

The shown paths are correct, the files are there and they have content.

Thanks for your help!

Your file paths appear to have spaces in them. What happens if you put "$log" in quotes when you define $attachment ?

Better solution: to avoid all that fussing around with parsing strings out of text files, don't output your file list to text. Just use the file system objects.

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

(Not tested, so check the command returns the files you're looking for)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM