1

On my venture in learning PowerShell, I have hit into another issue which I would like to get your help in this.

I have a code below inside a try-catch but when an error occurs inside the try block it does not seem to send it to catch block.

The Code:

try{
        if ($isFileAvailable -gt 0){
             $hashArgumentWithAttachment = @{
                From = $From
                To = $To
                Subject = $Subject
                Body = $Body
                SmtpServer = $SMTPServer
                Port = $SMTPPort
                UseSsl = $true
                Credential = $smtpCredential 
                Attachments = $filePath
            }

            Send-MailMessage @hashArgumentWithAttachment
        }
        Else {
            $hashArgumentWithOutAttachment = @{
                From = $From
                To = $To
                Subject = $Subject
                Body = $Body
                SmtpServer = $SMTPServer
                Port = $SMTPPort
                UseSsl = $true
                Credential = $smtpCredential 
            }

            Send-MailMessage @hashArgumentWithoutAttachment
        }
        Write-Output "Emailed"
        break
    }catch { 
        Write-Output "Error Occured, No of Attempts So far: " + $attempts.ToString()
    } 

On an instance where there is a Server connectivity error I expect to hit the catch block but instead it throws an error like this:

enter image description here

3
  • 2
    Try adding the erroraction to the cmdlet: Send-MailMessage -ErrorAction Stop Commented Apr 8, 2019 at 8:00
  • 1
    @BernardMoeskops thank you for your response. I think ErrorAction while solve my problem. Let me do some further testing and will have your answer confirmed! Thank you again! Commented Apr 8, 2019 at 8:39
  • 1
    @BernardMoeskops My tests seems to work well. Thank You very much. Mention it in the Answer section and I will have it confirmed in no time :) Commented Apr 9, 2019 at 4:04

1 Answer 1

1

Add ErrrorAction to the CMDLet:

Send-MailMessage @hashArgumentWithoutAttachment -ErrorAction Stop

Cheers!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.