title: Catch error from Send-MailMessage cmdlet when called from batch file
body: <p>I have a batch file that uses PowerShell's Send-MailMessage cmdlet to send emails out with status updates:</p>
  
  <pre><code>powershell -command " &amp; {Send-MailMessage -SMTPServer smtp.somewhere.com -From 'Sender &lt;sender@email.com&gt;' -To 'Recipient &lt;recipient@email.com&gt;' -Subject 'Subject' -Body 'Body' -Attachments 'D:\Logs\Log.log';}"
  if %ERRORLEVEL% neq 0 (
  echo ERROR - Something went wrong sending the email
  goto Error
  )
  </code></pre>
  
  <p>If the Send-MailMessage command fails (e.g. if attachment file not found, or other error), the %ERRORLEVEL% is not raised above 0.</p>
  
  <p>Other answers suggest adding explicit exit codes into a PowerShell script to return a code, but I can't find anything about how to capture an error if using a built in PS cmdlet like Send-MailMessage.  Can it be done, or do I need to wrap Send-MailMessage in another PS script?</p>