新错误处理

时间:2017-05-09 13:24:24

标签: powershell

我设置的路径无效,当复制失败时我想向某人发送电子邮件。如果没有错误,则发送一封电子邮件,说明副本成功。 目前它不会给我一个错误,它不会发送电子邮件。我知道电子邮件部分是正确的,并确认它确实有效。

我的脚本块。

try
{
 Copy-Item -path "\\main-
 4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force -ErrorAction Stop
 }
catch
 {
 $from = "alerts@domain.com"
 $to = "me@domain.com"
 $subject = "Copy Failed"
 $body = "The Copy failed to complete, please make sure the servers rebooted"
 $msg = "$file"
 $Attachment = "$file"

 $msg = new-object Net.Mail.MailMessage  
 $smtp = new-object Net.Mail.SmtpClient("mail.domain.com")  
 $msg.From = $From 
 $msg.To.Add($To)
 if($Attachment.Length -gt 1)
 {
    $msg.Attachments.Add($Attachment)
 }
 $msg.Subject = $Subject 
 $msg.IsBodyHtml = $true  
 $msg.Body = $Body 
 $smtp.Send($msg)
 }

1 个答案:

答案 0 :(得分:2)

如何在不重复电子邮件发送代码的情况下,为失败和成功发送电子邮件的解决方案如何:

$Status = 'Succeeded'
try{
    Copy-Item -path "\\main-4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force -ErrorAction Stop
}catch{
    $Status = 'Failed'
}finally{
    $from = "alerts@domain.com"
    $to = "me@domain.com"
    $subject = "Copy $Status"
    $body = "The Copy $Status"
    If ($Status = 'Failed') {$body += ", please make sure the server is rebooted" }

    $Attachment = "$file"
    $msg = new-object Net.Mail.MailMessage  
    $smtp = new-object Net.Mail.SmtpClient("mail.domain.com")  

    $msg.From = $From 
    $msg.To.Add($To)

    if($Attachment.Length -gt 1){
        $msg.Attachments.Add($Attachment)
    }

    $msg.Subject = $Subject 
    $msg.IsBodyHtml = $true  
    $msg.Body = $Body 
    $smtp.Send($msg)
}

您实际上不需要使用Finally块,但它确实创建了一个很好的代码块来明确电子邮件功能所属的内容。