0

In a set of Powershell scripts, I need to detect whether the SMTP server is down when I attempt to send an email with Send-MailMessage. If it is down, the code needs to make a phone call to Dev Ops, then continue with the rest of the scripts. In a test script, I have a try/catch that calls Send-MailMessage with bogus parameters so that the call will fail. This does throw an exception that shows up like this:

At C:\temp\XERES\smtpFailure\Test-ReturnErrorCode.ps1:12 char:9
+         Send-MailMessage -SmtpServer $SMTPServer -To $Recipients -Fro ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

However, I can't get my catch block to run.

The file with the try/catch looks like this:

    $SMTPServer = "IAmDown"
    $FromAddress = "someone@somewhere.com"
    $subject = "I was here"
    $Subject = "$($env:COMPUTERNAME): $($Subject)"
    $Recipients = "email@test.com"
    $Message = "I won't be sent"

    $errorMessage = ""
    
    try {
        Send-MailMessage -SmtpServer $SMTPServer -To $Recipients -From $FromAddress -Subject $Subject -Body $Message
        $errorMessage = $Error[0]
    } 
    catch [System.Net.Mail.SmtpException] {
        $errorMessage = "In catch: $($Error[0])"
    }

    return $errorMessage
}

The code that calls that file looks like:


$returnCode = Test-ReturnErrorCode 

Write-Host $returnCode

Write-Host "LASTEXITCODE = $LASTEXITCODE"

What prints out is always:

The remote name could not be resolved: 'IAmDown'
LASTEXITCODE = 

I can't get the "In catch" text to show, indicating the catch block ran, and $LASTEXITCODE is always empty. An exception is clearly being thrown -- how do I catch it?

Erica Ackerman
  • 189
  • 1
  • 2
  • 11
  • When a library captures an exception you will not be able to capture same exception unless the library contains a THROW. – jdweng Jan 30 '23 at 17:16
  • 1
    In short: `try` / `catch` only acts on _terminating_ errors, whereas it is far more typical for cmdlets to report _non-terminating_ errors. For the `catch` block to get invoked, non-terminating errors must be promoted to terminating ones by passing `-ErrorAction Stop` or by setting `$ErrorActionPreference = 'Stop'` beforehand. See the linked duplicate for more information. – mklement0 Jan 30 '23 at 17:17

0 Answers0