我在帐户到期通知电子邮件中使用了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被设置为“Send fail”)。finally块之后的最后一个else语句也起作用(如果没有帐户的电子邮件地址$countnotsent递增并且$sent被设置为“No”)。
1条答案
按热度按时间yeotifhr1#
$Error
变量是到目前为止在 * 整个会话 * 中发生的所有错误的运行日志,因此除非事先运行$Error.Clear()
,否则if ($error.Count -eq 0) { ... }
可能会出现误报一个简化的例子:
但是,如果
catch
块不会中止执行,则甚至不需要finally
块: