0

Im trying to catch the error set default value. Im confused how to do it. If the smtp is incorrect i would like to set the default value in smtp relay. Sorry im really new powershell and scripting.

    if ($To -eq "")
    {
    write-host "use the default value test2@test.com"
    $To = "test2@test.com"
    }
    if ($From -eq "")
    {
    write-host "use the default value MailboxReport"
    $From = "MailboxReport@test.com"
    }
    if ($Subject -eq "")
    {
    write-host "use the default value MailboxReport"
    $Subject = "MailboxReport"
    }
    if ($body -eq "")
    {
    write-host "use the default value mail"
    $body = "mail" 
    }
    if ($SmtpServer -eq "") 
    {
       write-host "use the default value XX.XXX.XXX.XX"
       $SmtpServer = "XX.XXX.XXX.XX"
    }

Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport
write-host "******************MailSent******************"

Error

Send-MailMessage : The remote name could not be resolved: '1235656+' At C:\Scripts\Exchange\Mailbox.ps1:309 char:21 + Send-MailMessage <<<< -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport + CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

0

You mean something like this:

try{
    Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport -ErrorAction Stop
}
catch{
    $SmtpServer = "XX.XXX.XXX.XX" #default server
    Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport
}
  • You need to force -ErrorAction Stop common parameter (apply to Send-MailMessage) to handle non-terminating errors as well using Try - Catch - Finally blocks. – JosefZ Mar 27 '18 at 18:56
  • Good call...fixed – EBGreen Mar 27 '18 at 18:59
  • thank for the responsed. I did this. Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport -EV error if($error){$SmtpServer = "XX.XXX.XXX.XX" Send-MailMessage -to $To -From $From -Subject $Subject -Body $body -SmtpServer $SmtpServer -Attachments $Filereport } – Renz Mar 28 '18 at 14:46
  • Don't use $error. That is a collection of all the errors that have happened in the session. I sometimes do what you are trying to do by using if(!$?){} that will basically say "If the last operation did not return a success then do this" – EBGreen Mar 28 '18 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.