错误处理程序无法捕获PowerShell中的错误

时间:2019-04-08 07:26:41

标签: windows powershell

在学习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块,但会引发如下错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

将ErrrorAction添加到CMDLet:

Send-MailMessage @hashArgumentWithoutAttachment -ErrorAction Stop

干杯!