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?

2
  • 1
    -Attachments $_attachments.FullName <-- make sure you pass the rooted path of the file to -Attachments Commented Feb 18, 2022 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 for more information. Commented Feb 19, 2022 at 15:13

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.