title: ForEach-Object Powershell write error per iteration
body: <p>Sorry for the bad title, but I'm having trouble describing this with brevity.</p>
  
  <p>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:</p>
  
  <pre><code>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 }
  </code></pre>
  
  <p>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.</p>
  
  <p>I've figured out how to pipe the errors to a file using:</p>
  
  <pre><code>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&gt;&gt; error.txt
  </code></pre>
  
  <p>However, this does not give me any specific information on which  line of the CSV it failed on.</p>
  
  <p>According to Microsoft's documentation for the Send-MailMessage Cmdlet it does not provide any output. </p>
  
  <p>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. </p>
  
  <p>Any help would be immensely appreciated. </p>