I am new in powershell. I want to get the events from Task Scheduler/Operational with code of failure, and send an email with all events in the body.
# Get all events from yesterday with ID=103 and Text, put in table and send email
# Get the event entries.
$eventEntries = & {Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-TaskScheduler/Operational'; StartTime=(Get-Date).AddDays(-1); ID='103'} |
Where {$_.Message.Contains('Task Scheduler failed to start instance')} |
select -Property ID,TimeCreated,Message |ft -wrap}
# Create a table row for each entry.
$array = @()
foreach ($eventEntry in $eventEntries)
{
$array += $eventEntry
}
$array | Format-table
# Create the email.
$MailFrom = "helpdesk@mydomain.com"
$MailTo = "myemail@mydomain.com"
$Subject = "EventLogAlert"
$email = New-Object System.Net.Mail.MailMessage( $MailFrom , $MailTo )
$email.Subject = $Subject
$email.IsBodyHtml = $true
$email.Body = @"
<table style="width:100%;border">
<tr>
<th style="text-align: center; padding: 5px;">ID</th>
<th style="text-align: center; padding: 5px;">TimeCreated</th>
<th style="text-align: center; padding: 5px;">Message</th>
</tr>
$array
</table>
"@
# Send the email.
$SmtpServer = "smtp.mail.outlook.com"
$SmtpPort = 587
$SmtpUser = "helpdesk@mydomain.com"
$SmtpPassword = "passwordexample"
$SMTPClient=New-Object System.Net.Mail.SmtpClient($SmtpServer,$SmtpPort)
$SMTPClient.EnableSsl=$true
$SMTPClient.Credentials= New-Object System.Net.NetworkCredential($SmtpUser,$SmtpPassword);
$SMTPClient.Send($email)
The $array is created with values in it, can viewed with echo $eventEntries
The result $email is not with values from table, it give this text
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Microsoft.Powershell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.PowerShell.Commands.Internal.Format.FormatEndData
Can somebody help me to write correct code to view all events in email.
And additionally, to create for each event an email separately.
Thanks in advance!