Sorry for the bad title, but I'm having trouble describing this with brevity.
I wrote a Powershell script that sends an email with a specific attachment to a list of users in a CSV. The script does what it is supposed to do. I am importing a CSV and piping it to ForEach-Object. Ex:
Import-Csv $csvFile | ForEach-Object{Send-MailMessage -To $($_.email) -Attachments $attachPath$($_.attachment) -SmtpServer $mailServer -Credential $credential -UseSsl $subject -Port $mailServerPort -Body "Hello $($_.name),$body" -From $sender -BodyAsHtml }
Again, this works as intended. The issue I have is that if there is an error I have no idea which iteration of the loop it occurred in.
I've figured out how to pipe the errors to a file using:
Import-Csv $csvFile | ForEach-Object{Send-MailMessage -To $($_.email) -Attachments $attachPath$($_.attachment) -SmtpServer $mailServer -Credential $credential -UseSsl $subject -Port $mailServerPort -Body "Hello $($_.name),$body" -From $sender -BodyAsHtml } 2>> error.txt
However, this does not give me any specific information on which line of the CSV it failed on.
According to Microsoft's documentation for the Send-MailMessage Cmdlet it does not provide any output.
I'd be happy if it would just print the $_.email along with the error to error.txt but everything I've tried doesn't work.
Any help would be immensely appreciated.