在power shell脚本中通过outlook发送电子邮件时出错

时间:2016-10-17 14:03:05

标签: email powershell outlook

我有一个PowerShell脚本如下。在这里,我检查是否在5分钟之前创建了任何.err文件,如果是,那么我发送的每个错误文件的电子邮件都包含.err文件的前5行。当我尝试运行脚本时,我收到一封电子邮件第一个文件,但我得到第二个文件的错误,如下面的快照所示。我是powershell的新手,我正在努力为这个错误寻找任何解决方案。

$ChkFile = "D:\ErrorLog\*.err"
$ChkFilePath = "D:\ErrorLog"
$o = New-Object -comObject Outlook.Application
$mail = $o.CreateItem(0)
$mail.importance = 2
$mail.subject = “Error Log“
$mail.To = “email@email.com“
$FileExists = Test-Path $ChkFile
$FileCount = Get-ChildItem $ChkFilePath *.err | Measure-Object | %{$_.Count}
If ($FileExists -eq $True) {

    If ($FileCount -gt 0)
    {
         Foreach($file in (Get-ChildItem $ChkFile))
         {

             Write-Host $file
             $createtime = $file.LastWriteTime
             $nowtime = get-date
             if (($nowtime - $createtime).totalminutes -gt 5) 
             {
                $GetFileContent = Get-Content $file -totalcount 5
                $mail.body = $GetFileContent 
                Write-Host $GetFileContent 
                $mail.Send()

             }


         }


    }
}

执行脚本时生成错误: enter image description here

1 个答案:

答案 0 :(得分:1)

调用$mail.Send()方法后,您可能需要重新创建邮件对象。您可以通过将对象创建放在循环中来完成此操作。

$ChkFile = "D:\ErrorLog\*.err"
$ChkFilePath = "D:\ErrorLog"
$o = New-Object -comObject Outlook.Application
$FileExists = Test-Path $ChkFile
$FileCount = Get-ChildItem $ChkFilePath *.err | Measure-Object | %{$_.Count}
If ($FileExists -eq $True) {

    If ($FileCount -gt 0) {
     Foreach($file in (Get-ChildItem $ChkFile)) {
         Write-Host $file
         $createtime = $file.LastWriteTime
         $nowtime = get-date
         if (($nowtime - $createtime).totalminutes -gt 5) {
            $mail = $o.CreateItem(0)
            $mail.importance = 2
            $mail.subject = "Error Log"
            $mail.To = "email@email.com"
            $mail.importance = 2
            $mail.subject = "Error Log"
            $mail.To = "email@email.com"
            $GetFileContent = Get-Content $file -totalcount 5
            $mail.body = $GetFileContent 
            Write-Host $GetFileContent 
            $mail.Send()

         }
     }
  }
}