2017-05-09 53 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