Reputation: 300
I have a powershell script as below. Here I check whether any .err file has been created before 5 minutes and if yes, then I am sending an email for each error file with first 5 lines of the .err file.When I try to run the script I receive an email for the first file, but i get an error for the second file as shown in the snapshot below. I am new to powershell, and I am struggling to find any solution for this error.
$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 protected]“
$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()
}
}
}
}
Error generated while executing the script:
Upvotes: 0
Views: 205
Reputation: 10044
After you invoke the $mail.Send()
method you will likely need to recreate your mail object. You could do this by placing the object creation in the loop.
$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 protected]"
$mail.importance = 2
$mail.subject = "Error Log"
$mail.To = "[email protected]"
$GetFileContent = Get-Content $file -totalcount 5
$mail.body = $GetFileContent
Write-Host $GetFileContent
$mail.Send()
}
}
}
}
Upvotes: 1