Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 错误处理新手_Powershell - Fatal编程技术网

Powershell 错误处理新手

Powershell 错误处理新手,powershell,Powershell,我设置的路径无效,当复制失败时,我想向某人发送电子邮件。如果没有错误,则发送电子邮件说明复制成功。 当前它没有给我一个错误,也没有发送电子邮件。我知道电子邮件部分是正确的,并确认它确实有效 我的脚本块 try { Copy-Item -path "\\main- 4\info\SmartPlant\app\CitrixRelease\domain\app\*" -Destination "\\domain.com\citrix\Installation Media\app\" -force

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

我的脚本块

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)
 }

这是一个解决方案,既可以发送失败的电子邮件,也可以发送成功的电子邮件,而无需重复电子邮件发送代码:

$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
块,但它确实创建了一个很好的代码块来明确电子邮件功能所属的内容。

现在,您只会在出现异常时发送邮件。您当前的copy命令会引发异常吗?我在try..catch上写了一篇博文,这可能会对您有所帮助:对,我想我拥有您所拥有的。只是不确定出了什么问题。我在错误操作结束时删除了停止,现在它可以工作了。奇怪的是,我原以为您需要使用
-erroraction stop
,否则错误可能不会终止。但如果它起作用,它也会起作用。