在PowerShell脚本中,Try-Catch-Finally无法与Send-Mailmessage一起使用

yquaqz18  于 2022-12-13  发布在  Shell
关注(0)|答案(1)|浏览(125)

我在帐户到期通知电子邮件中使用了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”)。

yeotifhr

yeotifhr1#

  • 自动$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"

相关问题