2017-05-09 56 views
1

我设置的路径无效,当复制失败时我想发送电子邮件给某人。如果没有错误,则发送电子邮件,说明复制成功。 目前它不给我一个错误,它不发送电子邮件。我知道电子邮件部分是正确的,并确认它可以正常工作。错误处理新手

我的脚本块。

try 
{ 
Copy-Item -path "\\main- 
4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force -ErrorAction Stop 
} 
catch 
{ 
$from = "[email protected]" 
$to = "[email protected]" 
$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) 
} 
+0

现在您只会在发生异常情况下发送邮件。您当前的复制命令是否会引发异常? – Seth

+0

我在try..catch上写了一篇博文,可能会帮助你:http://wragg.io/powershell-try-catch/ –

+0

对,我想我有你的。只是不知道什么是错的。 – user770022

回答

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 = "[email protected]" 
    $to = "[email protected]" 
    $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块,但它确实创建了一个很好的代码块来明确电子邮件功能的属性。

+0

谢谢,这个工程。 – user770022