在学习PowerShell的过程中,我遇到了另一个问题,希望在此方面得到您的帮助。
我在try-catch
内有下面的代码,但是当try
块内发生错误时,似乎没有将其发送到catch
块。
代码:
try{
if ($isFileAvailable -gt 0){
$hashArgumentWithAttachment = @{
From = $From
To = $To
Subject = $Subject
Body = $Body
SmtpServer = $SMTPServer
Port = $SMTPPort
UseSsl = $true
Credential = $smtpCredential
Attachments = $filePath
}
Send-MailMessage @hashArgumentWithAttachment
}
Else {
$hashArgumentWithOutAttachment = @{
From = $From
To = $To
Subject = $Subject
Body = $Body
SmtpServer = $SMTPServer
Port = $SMTPPort
UseSsl = $true
Credential = $smtpCredential
}
Send-MailMessage @hashArgumentWithoutAttachment
}
Write-Output "Emailed"
break
}catch {
Write-Output "Error Occured, No of Attempts So far: " + $attempts.ToString()
}
在出现服务器连接错误的实例上,我希望击中catch块,但会引发如下错误:
答案 0 :(得分:1)
将ErrrorAction添加到CMDLet:
Send-MailMessage @hashArgumentWithoutAttachment -ErrorAction Stop
干杯!