Friday, 20 August 2021

Try Catch and Send Email

try
{
 It will generate error
}
catch
{
    Write-host $_.Exception.Message -ForegroundColor Yellow
    Write-host $_.Exception.ItemName -ForegroundColor Green
    $ErrorMessage = $_.Exception.Message 
    $FailedItem = $_.Exception.ItemName
    $cred = Get-Credential
    Send-MailMessage -From Sender@domain.com -To Recipient@domain.com -Subject "Script Failed!" -SmtpServer smtp.office365.com -Body "We failed to read file $FailedItem. The error message was $ErrorMessage" -Port 587 -Credential $cred -BodyAsHtml -UseSsl 
    Continue
}
 

No comments:

Post a Comment