我在帐户过期通知电子邮件中使用 try-catch-finally 块,并且不考虑 finally 块中的 if 条件:
Write-Host $sName " : Selected to receive email: password will expire in "$days
if (($emailaddress) -ne $null) {
try {
Send-Mailmessage -smtpServer $SMTPServer -from $MailSender -to $emailaddress -subject $subject2 -body $EmailBody -bodyasHTML -priority High -Encoding $textEncoding -ErrorAction Stop
}
catch {
write-host "Error: Could not send email to $recipient via $smtpServer"
$sent = "Send fail"
$countfailed++
}
finally {
if ($error.Count -eq 0) {
write-host "Sent email for $sName to $emailaddress"
$countsent0++
}
}
} else {
Write-Host "$dName ($sName) has no email address."
$sent = "No"
$countnotsent++
}
期望 $countsent0 增加并且 $sent 设置为适当的消息。 catch 块有效($countfailed 递增并且 $sent 设置为“发送失败”)。 finally 块之后的最后一个 else 语句也有效(如果帐户没有电子邮件地址 $countnotsent 递增并且 $sent 设置为“否”)。
$Error
变量是迄今为止在整个会话中发生的所有错误的运行日志,因此除非您事先运行$Error.Clear()
,否则您可能会得到if ($error.Count -eq 0) { ... }
的误报
但是,由于您可能不想删除整个会话的此日志,因此请考虑使用简单的布尔变量来指示是否捕获了错误。
一个简化的例子:
$countsent0 = 0
$ok = $false # Helper Boolean variable.
try {
1 / 0 # Simulate an error that can be caught.
$ok = $true # At the end of this block, signal that no error occurred.
}
catch {
Write-Warning 'oops!'
}
finally {
if ($ok) { $countsent0++; Write-Host 'All''s well'. }
}
"`$countsent0: $countsent0"
但是,鉴于您的
catch
块不会中止执行,您甚至不需要 finally
块:
$countsent0 = 0
try {
1 / 0 # Simulate an error that can be caught.
# Getting here implies success.
$countsent0++
}
catch {
Write-Warning 'oops!'
}
"`$countsent0: $countsent0"
try
{
Send-MailMessage
}
catch [System.Net.Mail.SmtpException] {
Write-Host $_.Exception.Message
}