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 [email protected]"
    $To = "[email protected]"
    }
    if ($From -eq "")
    {
    write-host "use the default value MailboxReport"
    $From = "[email protected]"
    }
    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

1 Answer 1

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
}
4
  • 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
    Commented Mar 27, 2018 at 18:56
  • Good call...fixed
    – EBGreen
    Commented Mar 27, 2018 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
    Commented Mar 28, 2018 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
    Commented Mar 28, 2018 at 14:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .