1

The following code is part of my script to filter txt files > 0 KB and send them by e-mail as attachments.

$file_path = "\\path\to\my\files"
$file = Get-ChildItem -Path $file_path -Filter "*.txt" -Recurse | where-object {$_.Length -gt 0} | sort-object LastWriteTime -Descending

I 've got the following files inside my folder $file_path: test.txt | dummy1.txt | order.txt The result of $file is an array and I attache each single file to an e-mail and send it by using Send-MailMessage -To $_to -Subject $_subject -Encoding ([System.Text.Encoding]::UTF8) -Body $_body -BodyAsHtml -SmtpServer $_server -From $_from -Attachments $_attachments. This leads to an error, that the file could not be found.

Send-MailMessage : The "C:\WINDOWS\system32\test.txt" could not be found.

I don't understand, why the error comes? I mean, I defined the correct path in $file_path = "\\path\to\my\files" but the error messages shows a way different path C:\WINDOWS\system32\. If I use -Include instead of -Filter it works and my e-mail with the attached files will be send correctly without any issues. Why does -Filter leads to an error?

the_floor
  • 31
  • 5
  • 1
    `-Attachments $_attachments.FullName` <-- make sure you pass the rooted path of the file to `-Attachments` – Mathias R. Jessen Feb 18 '22 at 15:37
  • Also note that the problem, as described in Mathias' answer, only surfaces in _Windows PowerShell_, and there only _situationally_. In _PowerShell (Core) 7+_, the `[System.IO.FileInfo]` instances that `Get-ChildItem` outputs now _consistently_ stringify to their full path. See [this answer](https://stackoverflow.com/a/53400031/45375) for more information. – mklement0 Feb 19 '22 at 15:13

1 Answers1

2

The -Attachments parameter expects string arguments (the path(s) to the attachment(s)), but Windows PowerShell unfortunately converts the file info object to its name, "filename.txt". PowerShell then interprets the argument as a path relative to the current folder (eg. C:\Windows\System32), and you receive the error because that's not actually the location of the file.

To explicitly pass the rooted file path rather than just the file name, use the FullName property:

Send-MailMessage ... -Attachments $_attachments.FullName
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206