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?