Powershell – Catch the error on if statement powershell

powershell

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

Best Answer

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
}